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;
}
document.getElementsByTagName('option')
gives a collection of alloption
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 theselect
element, sodocument.getElementById("subs")
wouldn't find anything any more.If you just need to know if anything is selected check the
selectedIndex
property of theselect
element:EDIT: Changed
> 0
to<= 0
. I would assume that it should be checked if the user didn't select anything, too.You can check like this if
nothing
is going to be first (usually the case in my experience):To still compare based on the value, do this:
You may wand to change your markup so the label is beside, like this:
Otherwise this part:
.innerHTML = "Subject is Required!";
will erase your<select>
:)This should do it: