Johnny Johnny - 1 year ago 71
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">

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 Source

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

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

    if($('#s').val() == ''){
        return false;


    if($('#s').val() == ''){


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download