views:

41

answers:

3

Below are the options that i have in my 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>

and i want to create a javascript that well check if the user select a subject other than the first below what i tried using

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

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> :)

Nick Craver
You have written `document.getElementsByTagName('subs')` where you mean `document.getElementById('subs')`
RoToRa
@RoToRa - Oops copy error, thanks! and fixed.
Nick Craver
Thank you that did it,
Mahmoud
A: 

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.........
}
Sarfraz
A: 

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.

RoToRa
Your `if()` is backwards, if it's `> 0` nothing is **not** selected, he wants the reverse check.
Nick Craver
Well, in the text he wrote "if the user select a subject other than the first", but in in his example he tried to check if the first was selected, so there is a bit of a contradiction.
RoToRa
@RoToRa - He's adding a message *if they selected nothing*, it's backwards. This is **very** clear from his code, I'm not sure where the confusion is...
Nick Craver