Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
}
like image 966
Mahmoud Avatar asked Apr 20 '10 14:04

Mahmoud


2 Answers

You can check like this if nothing is the first option (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 want 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> :)

like image 110
Nick Craver Avatar answered Oct 31 '22 17:10

Nick Craver


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.........
}
like image 27
Sarfraz Avatar answered Oct 31 '22 17:10

Sarfraz