Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
727 views
in Technique[技术] by (71.8m points)

html - Check if dropdown's selected option is not the first with JavaScript

Below are the options that i have in my HTML code:

    <label id="subn">
      <select name="subs" id="subs">
        <option value="nothing">Choose a Subject</option>
        <option value="General Question">General Question</option>
        <option value="MemberShip Area">MemberShip Area</option>
        <option value="Others">Others</option>
      </select>
    </label>

I want to create JavaScript code that will check if the user selected an option other than the first.

Here is what I tried:

if (document.getElementsByTagName('option') == "nothing"){
    document.getElementById("subn").innerHTML = "Subject is Required!";
    document.getElementById("subs").focus();
    return false;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can check like this if nothing is going to be first (usually the case in my experience):

if (document.getElementById('subs').selectedIndex == 0){

To still compare based on the value, do this:

var sel = document.getElementById('subs');
if (sel.options[sel.selectedIndex].value == 'nothing') {

You may wand to change your markup so the label is beside, like this:

<select name="subs" id="subs"></select><label id="subn" for="subs"></label>

Otherwise this part: .innerHTML = "Subject is Required!"; will erase your <select> :)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...