Check if dropdown's selected option is not the

2019-01-27 23:48发布

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;
}

3条回答
戒情不戒烟
2楼-- · 2019-01-27 23:59

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.

查看更多
乱世女痞
3楼-- · 2019-01-28 00:11

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

查看更多
叛逆
4楼-- · 2019-01-28 00:15

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.........
}
查看更多
登录 后发表回答