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">
$(document).ready(function(){
    $("#keywords").focus(function() {
        if ($(this).val() == "<?php echo l('search_keywords'); ?>") {
            $(this).val("");
        }
    });
    $("#keywords").blur(function() {
        if ($(this).val() == "") {
            $(this).val("<?php echo l('search_keywords'); ?>");
        }
    });
});
</script>

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.

// SEARCH FORM
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>
    </form>
<?php }

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

Share or Bookmark This Post:


Comments

RSS Comments Feed


Tina's Avatar

Tina

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

Matt's Avatar

Matt

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.




(optional, not publicly displayed)


(optional)

Subscribe

RSS Feed

Archives

Powered by HTML5

HTML5 Powered with CSS3 / Styling, Multimedia, and Semantics