簡體   English   中英

HTML Form onsubmit不執行外部功能

[英]HTML Form onsubmit not executing the external function

我有一個HTML表單,並在提交時調用了validate()函數。

如果validate()函數位於“ body”標簽末尾的“ script”標簽內,則提交工作正常。

否則,即使使用document.ready,提交也不會在外部js文件中存在時調用調用validate()函數,例如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>

腳本-

    $(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;
    }
  };
});

我在這里錯過什么還是這可能是什么原因?

這是一個正在工作的更新小提琴 如果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()函數。

validate變量的作用域是您放入$(document).ready的匿名函數。 這意味着只能從該函數內部訪問它,而不能從位於全局范圍內的頁面訪問它。

使用$(...).submit函數添加事件偵聽器:

$(document).ready(function() {

    /* *** */

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

        /* *** */

    });
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM