为什么将提交事件与$(“#submitButton").submit(function(){})绑定不起作用? [英] Why does binding a submit event with `$("#submitButton").submit(function(){})` not work?
问题描述
我正试图弄清为什么 $(#submitButton").submit(function(){});
无法正常工作.
I’m trying to figure out why $("#submitButton").submit(function() {});
is not working.
我有这个< form>
:
<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>
我已经在jQuery中编写了此AJAX代码,以将值传递给服务器.
I’ve written this AJAX code in jQuery to pass values to the server.
<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() {}
});
});
});
</script>
如果我使用 .click(function(){
... })
,一切正常,但这将调用 updateViewing-helper.php
,而不用< input>
和< button>
元素提交表单.这意味着用户可以跳过输入密码的操作,只需单击按钮即可.
Everything works fine if I use .click(function(){
…})
, but this will call the updateViewing-helper.php
without submitting the form with the <input>
and <button>
elements. This means the user can skip putting their password in, and just click the button.
我尝试使用 .submit(function(){
... })
,然后使用 e.preventDefault()
,然后全部传递值导入AJAX,然后通过AJAX调用 updateViewing-helper.php
,然后我可以检查与服务器端匹配的密码.
I tried to use .submit(function(){
…})
, then use e.preventDefault()
, then pass all values into AJAX, then call the updateViewing-helper.php
via AJAX, then I can check for the password matching server-side.
但是 .submit
事件不起作用:没有警报或其他任何内容.
But the .submit
event is not working: there is not alert or anything.
推荐答案
调用不在表单上的提交按钮
Call submit on form not on the button
首先将id设置为
<form id="myForm">
然后调用此ID提交
$( document ).ready(function() {
$("#myForm").submit(function(){
});
});
这篇关于为什么将提交事件与$(“#submitButton").submit(function(){})绑定不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!