Blog

03 Sep
2013

jQuery Icon Logo

Prevent Empty Searches in WordPress Revised


I had an issue in WordPress where blank searches were still being passed and bringing back results. So I had to find a way of stopping it from being submitted. Searching the web I found this nice little solution/snippet of code from (PAGE/URL NO LONGER EXISTS): http://callmenick.com/2013/04/24/prevent-empty-searches-in-wordpress/

/**
 * A simple script to prevent empty searches
 */
$(document).ready(function(){        
    $('#searchform').submit(function(e) { // run the submit function, pin an event to it
        var s = $( this ).find("#s"); // find the #s, which is the search input id
        if (!s.val()) { // if s has no value, proceed
            e.preventDefault(); // prevent the default submission
            alert("Your search is empty!"); // alert that the search is empty
            $('#s').focus(); // focus on the search input
        }
    });
});

But the only issue I could find was that if somebody tried to be clever and typed in a few spaces for the search value, it would get passed the above script and allow the form to be submitted. As the author of the script wrote you need to use the jQuery .trim function to get around this. So here is a revised version which simply trims the value of any spaces at the start and end.

/**
 * A simple script to prevent empty searches
 */
$(document).ready(function(){        
    $('#searchform').submit(function(e) { // run the submit function, pin an event to it
        var s = $( this ).find("#s").val($.trim($( this ).find("#s").val())); // find the #s, which is the search input id and trim any spaces from the start and end
        if (!s.val()) { // if s has no value, proceed
            e.preventDefault(); // prevent the default submission
            alert("Your search is empty!"); // alert that the search is empty
            $('#s').focus(); // focus on the search input
        }
    });
});
Posted in: < CMS >
me@grafxflow avatar

me@grafxflow


I am a Full-stack Developer who also started delving into the world of UX/UI Design a few years back. I blog and tweet to hopefully share a little bit of knowledge that can help others around the web. Thanks for stopping by!

Visitors also viewed these posts

4 Thoughts

  1. 04 Sep
    2013

    avatar

    callmenick

    Thanks for the credit!
  2. 09 Sep
    2013

    avatar

    me@grafxflow

    Glad to give credit where it's due. Your code was a nice piece of work. Very handy.
  3. 22 Jul
    2018

    avatar

    Liman

    Where do I add this code?
  4. 22 Jul
    2018

    avatar

    me@grafxflow

    Add it to universal footer of your theme inside a 'script' tag.

    I am guessing by default you will be using jQuery so place it below this.

Add comment

Add comment