Note that there are some explanatory texts on larger screens.

plurals
  1. POCorrect way to validate input of a select element
    text
    copied!<p>What is the correct way to validate if an option is selected on a dropdown? I have some select elements (fieldset) which are set to display none and others that are visible. I want to validate only the ones that are visible, otherwise the form won't submit.</p> <p>For Example:</p> <pre><code>&lt;fieldset id="a1_1"&gt; &lt;select name="a1_1"&gt; &lt;option value="" selected="selected"&gt;Select Age&lt;/option&gt; &lt;option value="1"&gt;1&lt;/option&gt; &lt;option value="2"&gt;2&lt;/option&gt; &lt;/select&gt; &lt;/fieldset&gt; &lt;fieldset id="a1_2" style=" display: none;"&gt; &lt;select name="a1_2"&gt; &lt;option value="" selected="selected"&gt;Select Age&lt;/option&gt; &lt;option value="1"&gt;1&lt;/option&gt; &lt;option value="2"&gt;2&lt;/option&gt; &lt;/select&gt; &lt;/fieldset&gt; &lt;fieldset id="a2_1"&gt; &lt;select name="a2_1"&gt; &lt;option value="" selected="selected"&gt;Select Age&lt;/option&gt; &lt;option value="1"&gt;1&lt;/option&gt; &lt;option value="2"&gt;2&lt;/option&gt; &lt;/select&gt; &lt;/fieldset&gt; &lt;fieldset id="a2_2" style=" display: none;"&gt; &lt;select name="a2_2"&gt; &lt;option value="" selected="selected"&gt;Select Age&lt;/option&gt; &lt;option value="1"&gt;1&lt;/option&gt; &lt;option value="2"&gt;2&lt;/option&gt; &lt;/select&gt; &lt;/fieldset&gt; </code></pre> <p>I was trying something like this without any luck:</p> <pre><code>var x = document.forms["x"]["a1_1"].value; if (x == null || x == "") { alert("Age must be selected"); return false; } </code></pre>
 

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