Check if dropdown's selected option is not the first with JavaScript

前端 未结 3 1035
感动是毒
感动是毒 2020-12-20 20:35

Below are the options that i have in my HTML code:

    
提交评论

  • 2020-12-20 20:51

    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.

    0 讨论(0)
  • 2020-12-20 21:03

    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.........
    }
    
    0 讨论(0)
  • 提交回复
    热议问题