HTML表单提交不执行外部函数

时间:2016-05-19 15:45:27

标签: javascript jquery html forms

我有一个HTML表单,在提交时,要调用一个validate()函数。

如果validate()函数位于“body”标记末尾的“script”标记内,则提交工作正常。

否则,即使使用document.ready,提交也不会调用validate()函数,因为它存在于外部js文件中,如https://jsfiddle.net/vg47127o/1/

HTML -

<form method="post" action="#" onsubmit="return validate()" name="loginForm" class="form-horizontal" role="form">

<div class="form-group">
<p class="error-block"><span class="glyphicon glyphicon-exclamation-sign"> </span> <span class="error-msg"></span></p>
 </div>

<div class="form-group">
<label class="control-label col-sm-3" for="username">username:
</label>

<div class="col-sm-9">
  <input type="text" class="form-control digits-only" id="username" placeholder="Enter Username">
</div>
</div>

<div class="form-group">
<label class="control-label col-sm-3" for="password">Password:</label>
<div class="col-sm-9">
  <input type="password" class="form-control" id="password" placeholder="Enter Password">
</div>
</div>

<div class="form-group">
<div class="col-sm-offset-4 col-sm-8">
  <button type="submit" id="loginBtn" class="btn btn-default">Log In</button>
  <button type="reset" class="btn btn-default">Reset</button>
</div>
</div>
</form>

SCRIPT -

    $(document).ready(function() {

  var displayError = function(error, msg) {
    $(".error-block .error-msg").text(msg);
    if (error === true)
      $(".error-block").show();
    else
      $(".error-block").hide();
    return true;
  };

  //Validating the input fields    
  var validate = function() {
    var $username = $("#username").val(),
      $password = $("#password").val();

    if ($username === '' || $password === '') {
      displayError(true, ' Username or Password cannot be empty. ');
      return false;
    } else if ($username.length < 6 || $password.length < 6) {
      displayError(true, ' Username and Password should be a minimum of 6 characters. ');
      return false;
    } else {
      displayError(false, ' ');
      return true;
    }
  };
});

我在这里错过了什么或者可能是什么原因。

2 个答案:

答案 0 :(得分:1)

这是一个有效的updated fiddle。如果validate不返回true,则需要捕获submit()事件。

这是你在jQuery中包含的内容:

$("form").on("submit", function (event) {
    if (!validate()) {
        event.preventDefault();
    }
});

然后,您的<form>标记只是<form method="post" action="#" name="loginForm" class="form-horizontal" role="form">

FYI

这样做的原因是,当您的validate()函数在文档内部准备就绪时,它的作用域是文档就绪函数,因此,内联DOM事件触发器无权访问它。您必须在jQuery函数中设置事件处理程序,或在文档就绪函数之外声明您的validate()函数。

答案 1 :(得分:1)

validate变量的范围限定为您放入$(document).ready的匿名函数。这意味着它只能从该函数内访问,而不能从位于全局范围内的页面访问。

使用$(...).submit函数添加事件侦听器:

$(document).ready(function() {

    /* *** */

    //Validating the input fields    
    $("[name=loginForm]").submit(function() {
        var $username = $("#username").val(),
            $password = $("#password").val();

        /* *** */

    });
});
相关问题