Written by me@grafxflow
03 Sep, 2013
4
5,963
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
}
});
});
24 Nov, 2013
07 Nov, 2012
22 Nov, 2009
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!
Follow11 Jul, 2023
21 Jun, 2023
Views: 166,435
Views: 40,390
Views: 37,138
Views: 33,666
4 Response
callmenick
04 Sep 2013
Thanks for the credit!
me@grafxflow
09 Sep 2013
Glad to give credit where it's due. Your code was a nice piece of work. Very handy.
Liman
22 Jul 2018
Where do I add this code?
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.