表单validate()函数未被调用

时间:2014-05-22 03:56:08

标签: javascript forms validation

我创建了一个表单,我希望我的JavaScript通过检查人名的长度是> 20来验证我的表单。如果它是我试图使弹出警报出现,但它不起作用。它什么都不做。

这是我的HTML:

<form name = "enrol" onsubmit="validate()">
  <h3>Please complete the form below. Mandatory fields marked with *</h3>
  <fieldset>
    <h4>Personal Details</h4>
    <p>
      <label for="fname">*First Name</label> <input type="text" name="fname" id="fname" placeholder="First Name" />
    </p>
    <p>
      <label for="lname">*Last Name</label> <input type="text" name="lname" id="lname" placeholder="Last Name" />
    </p>
  </fieldset>
</form> 

这是我通过引用连接的JavaScript。除函数validate ()

外,所有其他脚本都有效
window.onload = function() {
  console.log("The window has finished loading");
  var SubmitButton = document.getElementById("SubmitButton");
  SubmitButton.addEventListener('click', function() {
    document.getElementById("SubmitButton").click();
  }, false);
  console.log("The submit button has been clicked");

  var fname = document.getElementById("fname");
  fname.addEventListener('keyup', function() {
    console.log((fname).value);
  }, false);

  var lname = document.getElementById("lname");
  lname.addEventListener('keyup', function() {
    console.log((lname).value);
  }, false);

  function validate(){
    var fname = document.enrol.fname.value;
    var lname=document.enrol.lname.value;
    if(fname.length>20){
      alert("Value can't exceed 20");
    }
    if(lname.length>20){
      alert("Value can't exceed 20");
    }
  }

2 个答案:

答案 0 :(得分:1)

validate函数放在window.onload事件处理程序之外。

window.onload = function() {
    console.log("The window has finished loading");


    var SubmitButton = document.getElementById("SubmitButton");
    SubmitButton.addEventListener('click', function() {
    document.getElementById("SubmitButton").click();}, false);
    console.log("The submit button has been clicked");


    var fname = document.getElementById("fname");
    fname.addEventListener('keyup', function() {
    console.log((fname).value);}, false);

    var lname = document.getElementById("lname");
    lname.addEventListener('keyup', function() {
    console.log((lname).value);}, false);
}

function validate()
{

    var fname = document.enrol.fname.value;
    var lname=document.enrol.lname.value;

    if(fname.length>20)
    {
        alert("Value can't exceed 20");
    }
    if(lname.length>20)
    {
        alert("Value can't exceed 20");
    }
}

答案 1 :(得分:0)

这是因为全局范围中无法访问validate()函数。原因是因为它位于分配给window.onload的匿名函数内部,因此只能在该函数内部调用。

要修复它,只需在}功能的结束window.onload后移动它。