Written by me@grafxflow
03 Sep, 2013
4
5,589
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
30 Apr, 2017
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
25 Nov, 2022
20 Sep, 2022
Views: 162,627
Views: 38,815
Views: 34,607
Views: 31,977
4 Response
callmenick
04 Sep 2013me@grafxflow
09 Sep 2013Liman
22 Jul 2018me@grafxflow
22 Jul 2018I am guessing by default you will be using jQuery so place it below this.