I have this basic Wordpress search form, I don't want users to be able to search if they leave the search field blank, preferably with javascript, how is this done?
Asked
Active
Viewed 3,754 times
1
-
add a javascript test: if $("#the-search-field").val() == '') do nothing; – Jeremy Jan 28 '16 at 10:42
3 Answers
2
Many ways lead to Rome... But here is one solution.
So, say your search form input field has and id
called query
and you want to disable the submit
button until the user has entered at least 1 character.
$('#query').keyup(function () {
if ($(this).val() == '') {
$('#submit').prop('disabled', true);
} else {
$('#submit').prop('disabled', false);
}
}).keyup();
See this fiddle: https://jsfiddle.net/fxqsc86s/

Hidde
- 103
- 7
1
(function() {
$('form > input').keyup(function() {
var empty = false;
$('form > input').each(function() {
if ($(this).val() == '') {
empty = true;
}
});
if (empty) {
$('#search').attr('disabled', 'disabled');
} else {
$('#search').removeAttr('disabled');
}
});
})();
and remember to disable the button by default:
<input type="submit" id="search" value="Search" disabled="disabled" />
Answer taken from previous stack overflow question: Disabling submit button until all fields have values

Community
- 1
- 1

fully stacked geek
- 536
- 4
- 10
0
You can also do it like this.
It will check either your TextBox is empty
if ($('#TextBoxId').val() === '') {
// Your coding will go here.
}

Mustaasam Saleem
- 166
- 8