1

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?

Brad Fletcher
  • 3,547
  • 3
  • 27
  • 42

3 Answers3

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
0

You can also do it like this.
It will check either your TextBox is empty

if ($('#TextBoxId').val() === '') {
// Your coding will go here.
}