HTML Select Option Validation

asdwal picture asdwal · Jan 1, 2014 · Viewed 29.6k times · Source

How would I alert out that the selection must not be be blank in plain javascript?

Here is my code for my option menu:

            <div class="interest">
            <label for="interest">Interest Area *</label>

            <select name="interest">
            <option value="blank"></option>
            <option value="option1"> EXAMPLE 2 </option>
            <option value="option2"> EXAMPLE 3 </option>
            <option value="option3"> EXAMPLE 4 </option>
            </select>
            </div>

Thanks in advance

Answer

adeneo picture adeneo · Jan 1, 2014
document.getElementsByName('interest')[0].onchange = function() {
     if (this.value=='blank') alert('Select something !');
}

or in a submit handler or similar, just check the value

if ( document.getElementsByName('interest')[0].value == 'blank' )
    alert('Select something !');