Need with Javascript function for Select check

时间:2017-12-06 15:58:28

标签: javascript

I tried to create a function to check on a drop-down option on select box. It requires a user to select a user name before submit. I put '0' and check if this = 0, then return false, but it didn't work.

I added a function to check radio buttons and they all worked fine. However, the select Staff doesn't work. I mean, when I click on Submit after checking all radio boxes, it get submitted anyway. How do I fix it to make it work?

Can you help me?

<script language="javascript">
function validateForm(daForm) {
nCount = document.frmReport.txtCount.value;
    // check all rb radio buttons
    for (var i = 1; i < nCount; i++) {
        if (! getCheckedRadioValue(daForm["Report"+i])) {
            alert ("Please select a value for option " + i)
            return false
         }
if (UserID.options[UserID.selectedIndex].value == 0) {
                alert("Please select a user");
                return false
    }
    // add other checks here...
                alert ("Thank you!")
                window.open("Search.asp")
    return true
}
<body>
<form action="" method="post" id="newMenu" name="frmReport" onSubmit="return validateForm(this)">
    <select name="UserID">
          <option value=0>Staff name:</option>
          <option value=1>Jenny</option>
          <option value=2>David</option>
     </select>
    <input type="submit" value="Submit">
</form>

Thank you very much!

2 个答案:

答案 0 :(得分:1)

看起来选择器出了问题。

比较“0”值似乎工作得很好。我已经包含了一个显示此内容的片段。

简而言之,请更改此内容

if (UserID.options[UserID.selectedIndex].value == 0) {
     alert("Please select a staff");
     return false
}

到此

if (document.querySelector("[name='UserID']").value == 0) {
     alert("Please select a staff");
     return false
}

进行多项选择并提交以查看结果。

function validateForm(daForm){
  var select = document.querySelector("[name='UserID']")
  
  if(select.value == 0){
    console.log("Please select a value");
  }else{
    console.log("Selection made.");
  }

  return false;
}
<form action="" method="post" id="newMenu" name="frmReport" onSubmit="return validateForm(this)">
    <select name="UserID">
          <option value=0>Staff name:</option>
          <option value=1>Jenny</option>
          <option value=2>David</option>
     </select>
     
     <input type="submit">
 </form>

答案 1 :(得分:0)

您不能只使用UserID并使用JavaScript处理它。这是select元素的名称。您需要做的是使用JavaScript选择它然后使用它。

var UserID = document.getElementsByName("UserID")[0];
if (UserID.options[UserID.selectedIndex].value == 0) {
                alert("Please select a staff");
                return false
    }
    // add other checks here...
                alert ("Thank you!")
    return true;
}

<== Fiddle Me ==>