$(“ #submitButton”).submit(function(e){}); jQuery无法正常工作

时间:2019-03-19 18:42:55

标签: javascript php jquery html ajax

我整个上午都在努力弄清为什么我的$(“#submitButton”)。submit(function(){});不起作用。

我有一个带有2个标签的表单:

(输入类型=“ password”),以便用户在单击SubmitButton之前再次输入密码。

然后(按钮type =“ submit”)作为提交表单的按钮

<div class="card p-2">
   <form>
      <div class="input-group">
          <label for="inputPasswordAgain" class="sr-only">Password</label>
          <input type="password" id="inputPasswordAgain" class="form-control" placeholder="Please enter your password again!" required>

          <div class="input-group-append">
              <button type="submit" id="submitButton" name ="submitButton" class="btn btn-secondary btn-block">Submit Changes</button>
          </div>
       </div>
   </form>
</div>

因为在这段代码之前,我有一个表,其中填充了多行,所以每行都有一个删除按钮(这是另一种形式)。每行还具有一个选择下拉列表。整个表是动态的,是基于会话数组构建的。

由于表中的“删除”按钮是一种表单,因此我无法使用嵌套表单来提交用户针对每一行中每个选择下拉列表选择的内容。

因此,我创建了一个AJAX jQuery以从所有选择下拉列表中选择值,并将它们传递给updateViewing-helper.php。

<script type="text/javascript">
        $( document ).ready(function() {
            $( "#submitButton" ).click(function() {
                var data = {};
                var i;
                for (i = 0; i < $("#sessionQuantity").html(); i++) {
                    data[i] = $("#" + i).val();
                };
                $.ajax({
                    type: "POST",
                    url: "updateViewing-helper.php",
                    data: data,
                    success: function{blah blah blah}
                    }
                });
            });
        }); 
  </script>

一切正常,除了我使用.click(function(){})之外,但这将调用updateViewing.php而不提交上面的表单(一个带有输入标签和按钮标签的表单,又名用户可以跳过将其密码输入,然后单击按钮。)

因此,我尝试使用.submit(function(){}),然后使用e.preventDefault()阻止从表单进行实际提交,然后将所有下拉选择传递到AJAX中,然后调用updateViewing-helper。通过AJAX进行php,然后可以在updateViewing-helper php文件中检查密码是否匹配。

$( document ).ready(function() {
            $( "#submitButton" ).submit(function(e) {
                alert( "form submitted" );
                e.preventDefault();

                var data = {};
                var i; blah blah the code is the same as before

但.submit无法正常工作!没有弹出警报或其他任何内容。 任何建议表示赞赏!

1 个答案:

答案 0 :(得分:4)

调用不在按钮上的表单上的提交

首先将id设置为

<form id="myForm">

然后调用此ID提交

$( document ).ready(function() {
   $("#myForm").submit(function(){

    });
});
相关问题