Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You have several problems in your code.</p> <ul> <li>An <strong>ID can only be used once</strong> in a HTML document. You used <code>#gender</code> twice.</li> <li>You don't need to use another flag variable, you can run the <code>if</code> simply.</li> <li>In your second <code>if</code> you have not used <code>{}</code> brackets, thus <code>preventDefault</code> is always executing.</li> </ul> <p>I suggest you do something like this:</p> <pre><code>&lt;input type="radio" name="gender" value="male" /&gt; Male&lt;br /&gt; &lt;input type="radio" name="gender" value="female" /&gt; Female &lt;input type="submit" name="searchbutton" value="Search" id="searchbutton"&gt; </code></pre> <p>and the jQuery:</p> <pre><code>$('#searchbutton').click(function(event){ if ($('input[name="gender"]:checked').length &lt; 1) { alert("Select the field first"); event.preventDefault(); } }); </code></pre> <p><a href="http://jsfiddle.net/bazmegakapa/xg2jC/" rel="nofollow">Working Demo</a></p> <p><strong>Explanation</strong>: The <a href="http://api.jquery.com/attribute-equals-selector/" rel="nofollow">attribute selector</a> will match <code>input</code>s whose <code>name</code> is <code>gender</code>, and the <a href="http://api.jquery.com/checked-selector/" rel="nofollow"><code>:checked</code></a> selector only selects the ones that are checked. Then using <a href="http://api.jquery.com/length/" rel="nofollow"><code>length</code></a> we can see how many elements were matched. If zero, that means that the use has not selected any of the options.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload