Below are the options that i have in my HTML code:
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>
:)
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.
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.........
}