2

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>

4 Answers 4

7
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 !');
Sign up to request clarification or add additional context in comments.

Comments

0

You can use '.selectedIndex' to return the index of selected value and check if its equal to blank( 0 in your case) or not

if(0 == document.getElementsByTagName('select')[0].selectedIndex){
alert("Please select a value first")
return;
}

You can also use Jquery for selection instead of document.getElementsByTagName

Comments

0

I feel the easiest way to do it is with html using required on the select all the best

Interest Area *

        <select required 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>

Comments

-1

In general, check if the selectElement.value is "blank" in a simple if statement.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.