Search code examples
javascripthtmlvalidation

HTML Select Option Validation


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>

Solution

  • 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 !');