Use jQuery to clear and/or fill the search form instead of in-line javascript

Use  jQuery to clear and/or fill the search form instead of in-line javascript

I'm in the process of writing a jQuery/MySQL autocomplete mod for the sNews CMS system, (it's only halfway done, my search form uses jQuery autocomplete plugin now if you want to test) and I noticed a bunch of javascript inside the searchform function giving me problems.

Basically this is the functionality that clears the searchbox on clicking (onfocus) and then replaces it if you move away (onblur) without entering any search text. I have written this up jQuery style, so if you use jQuery, you can add this code in your index.php head to get the same results, and keep behavior out of your markup.

Now insert this code into your page, I usually put it at the bottom to load last, but you can add it in the head.

<script type="text/javascript">
    $("#keywords").focus(function() {
        if ($(this).val() == "<?php echo l('search_keywords'); ?>") {
    $("#keywords").blur(function() {
        if ($(this).val() == "") {
            $(this).val("<?php echo l('search_keywords'); ?>");

then BACK-UP your snews.php file and work off of a copy, now find the searchform function and strip the javascript inside the mark up.

function searchform() { ?>
    <form id="search_engine" method="post" action="<?php echo _SITE; ?>" accept-charset="<?php echo s('charset');?>">
        <p><input class="searchfield" name="search_query" type="text" id="keywords" value="<?php echo l('search_keywords');
?>" />
        <input class="searchbutton" name="submit" type="submit" value="<?php echo l('search_button')?>" /></p>
<?php }

All set, and you'll be ready for my autocomplete mod/add-on in the future as well ;).



You might like


Hi Matt,
thanks for this nice hack/mod :)
Quick question, have you currently deactivated the auto-completion on your site? since I can't seem to see it working here right now, to test ...
all the best

Hi Tina,

Yes, I removed it a while ago, it was based on a manually maintained set of keywords and phrases. There's no easy way to accurately pull that information dynamically.

One thing I've considered is re-doing it so it will give suggestions based on previous searches, but that poses another set of problems.

Comments are closed. No new comments allowed.

Copyleft 2002 - 2017 Matt Jones
Hand crafted with HTML5 & CSS3
↑ Back to top