smart search

Prevent Empty Searches in WordPress Revised

Written by me@grafxflow -
03 Sep, 2013

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

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!