表单验证问题(Javascript)

时间:2014-12-13 08:24:15

标签: javascript html

如果他没有点击复选框,我想限制用户提交表单。除Var Check外,一切正常。

<script>
function validateForm() {
var check = document.forms["myform"]["check"].value; 
if (check.checked == false) 
{
    alert ('Please Accept our Terms and Conditions ');
    return false;
}else {     
    return true;
}

}
 </script>

4 个答案:

答案 0 :(得分:1)

您可以尝试代码:

function validateForm() {
   if (document.getElementById("check").checked == false) 
   {
     alert ('Please Accept our Terms and Conditions ');
     return false;
   }else {     
     return true;
   }
}

答案 1 :(得分:0)

尝试使用ID选中复选框。 请看这个链接http://www.w3schools.com/jsref/prop_checkbox_checked.asp

实施例

//Find out if a checkbox is checked or not:

var x = document.getElementById("myCheck").checked;

//The result of x will be:

false or true

答案 2 :(得分:0)

您的输入复选框必须具有ID =&#34;复选框&#34;

 <form action="youraction" method="POST/GET" onSubmit="return validateForm();">
   .....
 </form>

function validateForm() {
 if(document.getElementById("checkbox").checked)
    return true;
 else 
   return false;
}

答案 3 :(得分:0)

你做错了:

var check = document.forms["myform"]["check"].value;
//it gives string value of checkbox
//string variable cannot refer to check-box state

&#13;
&#13;
var chk = document.myform.check; //checkbox

var validate = function() {
  var errors = []; //list of errors, in-case you have few more field to validate
  if (!chk.checked) {
    errors.push('You must accept the terms & conditions');
  }
  //do the rest of the validations
  if (errors.length) {
    alert(errors.join('\n')); //show all errors here
  }
  return !errors.length; //don't submit if errors
};
&#13;
<form name='myform' onsubmit='return validate()'><!-- validate on submit -->
  <input type='checkbox' name='check' />I accept terms &amp; conditions
  <input type='submit' />
</form>
&#13;
&#13;
&#13;