'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 whether the user selected an option other than the first one.

Here is what I tried:

if (document.getElementsByTagName('option') == "nothing"){
    document.getElementById("subn").innerHTML = "Subject is Required!";
    document.getElementById("subs").focus();
    return false;
}


Solution 1:[1]

This should do it:

var index = document.your_form_name.subs.selectedIndex;
var value = document.your_form_name.subs.options[index].value;

if (value === "nothing"){
   // your further code here.........
}

Solution 2:[2]

document.getElementsByTagName('option') gives a collection of all option elements in the document and "nothing" is a string. Comparing a collection to a string is quite useless.

Also setting document.getElementById("subn").innerHTML = "Subject is Required!"; will delete the select element, so document.getElementById("subs") wouldn't find anything any more.

If you just need to know if anything is selected check the selectedIndex property of the select element:

if (document.getElementById("subs").selectedIndex <= 0) {
  // nothing is selected
}

EDIT: Changed > 0 to <= 0. I would assume that it should be checked if the user didn't select anything, too.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Sarfraz
Solution 2