猿问

如何从多个选择HTML中选择值

我有一个选择此表格:


<form name="form" method="post" action="registr.php">

  <select name="type">

    <option value="std">Standard</option>

    <option value="stud">Student</option>

    <option selected hidden value=""></option>

  </select>

  <input type="submit" value="Invia" onclick="return validation();">

</form>

我必须检查使用javaScript函数发送的数据。如果我没有选择学生或标准生,则该表格必须返回false。这是函数,但是不起作用:


function validation() {

  var type = document.form.type.value;

  if (type == "") {

    return false;

  }

  return true;

}


弑天下
浏览 132回答 3
3回答

宝慕林4294392

您的脚本确实有效,您也可以尝试将添加id到您的选择选项:function validation() {&nbsp; var id = document.getElementById("selecttype");&nbsp; var type = id.options[id.options.selectedIndex].value;&nbsp; if (type == "") {&nbsp; &nbsp; return false;&nbsp; }&nbsp; return true;}&nbsp;&nbsp;<form name="form" method="post" action="registr.php">&nbsp; <select name="type" id="selecttype">&nbsp; &nbsp; <option value="std">Standard</option>&nbsp; &nbsp; <option value="stud">Student</option>&nbsp; &nbsp; <option selected hidden value=""></option>&nbsp; </select>&nbsp; <input type="submit" value="Invia" onclick="return validation();">&nbsp; </form>

九州编程

只需在表单标签onsubmit中调用验证方法,因为如果表单为假,则它将不提交,否则它将提交。<form name="form" method="post" onsubmit="return validation();" action="registr.php"><select name="type"><option value="std">Standard</option><option value="stud">Student</option><option selected hidden value=""></option></select><input type="submit" value="Invia"></form>

犯罪嫌疑人X

您应该将对验证功能的调用添加到表单本身的Submit事件中-而不是直接添加到按钮上。如果既未选择学生也未选择标准,以下示例将打开一个警报对话框。function validation() {&nbsp; var type = document.form.type.value;&nbsp; if (type == "") {&nbsp; &nbsp; alert("Please select something");&nbsp; &nbsp; return false;&nbsp; }&nbsp; return true;}<form name="form" method="post" action="registr.php" onsubmit="return validation();">&nbsp; <select name="type">&nbsp; &nbsp; <option value="std">Standard</option>&nbsp; &nbsp; <option value="stud">Student</option>&nbsp; &nbsp; <option selected hidden value=""></option>&nbsp; </select>&nbsp; <input type="submit" value="Invia"></form>
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答