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

Comments (2)

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 ;).

bookmark / share this: Bookmark and Share
rated 3/5 (6 votes)


2 comments

Add a new comment »

Tina Tina said:
Apr 7th, 2010 at 5:46 pm

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 Matt said:
Apr 8th, 2010 at 7:25 am

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.



Write a comment

* = required field

:

:

:

:

You may insert urls in plain text, urls will be automatically linkified for trusted users and on seasoned posts only. All first comments are moderated, so use your email if you want to be remembered.


Back to top