jQuery Icon Logo
me@grafxflow

Written by me@grafxflow

03 Sep, 2013

4

5,580

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

Add comment

4 Response

  1. avatar

    callmenick

    04 Sep 2013
    Thanks for the credit!
  2. avatar

    me@grafxflow

    09 Sep 2013
    Glad to give credit where it's due. Your code was a nice piece of work. Very handy.
  3. avatar

    Liman

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

    me@grafxflow

    22 Jul 2018
    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.

Smart Search

131 Following
57 Followers

me@grafxflow

Hull, United Kingdom

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!

Follow