Johnny Johnny - 3 months ago 7
jQuery Question

WordPress search - Do nothing if no search string has been entered

I have the following snippet of code:

<form id="searchform" method="get" action="<?php bloginfo('siteurl')?>/">
<input type="text" name="s" id="s" class="textbox" placeholder="Search" />
<input type="submit" id="t" value="&gt;" class="searchsubmit">
</form>


Unfortunately if no search string is entered, and the submit button is pressed or Enter is hit, then it takes you off to an undesired page.

For me this is the blog page as I can see the 'blog' class in the body.

How can I prevent the search from triggering until a string is entered?

Thanks for your time and help in advance.

Answer

One - You can use the HTML5 required attribute in your input tag

<input type="text" name="s" id="s" class="textbox" placeholder="Search" required/>

It's not fully supported in all browsers though and you can check that here https://developer.mozilla.org/en-US/docs/Web/HTML/Element/Input#Browser_compatibility

Two - Bind a submit handler to your form and check before submitting - that way it handles the button click plus enter key press in the form

$('#searchform').submit(function(){
    if($('#s').val() == ''){
        return false;
    }
});

or

$('#searchform').submit(function(e){
    if($('#s').val() == ''){
        e.preventDefault();
    }
});

FIDDLE

Comments