gpt4 book ai didi

javascript - 两个 HTML 表单冲突

转载 作者:行者123 更新时间:2023-11-28 15:31:15 25 4
gpt4 key购买 nike

我有两种相互冲突的形式我想更改“var form = $('form');”中的表单ID例如“var form = $('myForm');”如果我将 id 表单更改为 myForm,请告诉我,在这种情况下,在下面的代码中我如何合并:

 $(document).ready(function(){
var form = $('form');
var submit = $('#submit');

form.on('submit', function(e) {
// prevent default action
e.preventDefault();
// send ajax request
$.ajax({
url: 'ajax_comment.php',
type: 'POST',
cache: false,
data: form.serialize(), //form serizlize data
beforeSend: function(){
// change submit button value text and disabled it
submit.val('Submitting...').attr('disabled', 'disabled');
},
success: function(data){
// Append with fadeIn see http://stackoverflow.com/a/978731
var item = $(data).hide().fadeIn(800);
$('.comment-block').append(item);

// reset form and button
form.trigger('reset');
submit.val('Submit Comment').removeAttr('disabled');
},
error: function(e){
alert(e);
}
});
});
});

HTML 代码:

<form class="form-horizontal" role="form" id="form" method="post">
<!-- need to supply post id with hidden fild -->
<input type="hidden" name="filmId" value="<?php echo $row['filmId']?>">
<div class="form-group">
<div class="col-sm-2">
<label>Name *</label>
</div>
<div class="col-sm-10">
<input class="form-control" type="text" name="name" id="comment-name" placeholder="Your Name" required>
</div>
</div>
<div class="form-group">
<div class="col-sm-2">
<label>Email *</label>
</div>
<div class="col-sm-10">
<input class="form-control"type="email" name="mail" id="comment-mail" placeholder="Your Email" required>
</div>
</div>
<div class="form-group">
<div class="col-sm-2">
<label>Comment *</label>
</div>
<div class="col-sm-10">
<textarea class="form-control" rows="5" name="comment" id="comment" placeholder="Type your comment here...." required></textarea>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<input type="submit" class="btn btn-primary" id="submit" value="Submit Comment">
</div>
</div>
</form>

最佳答案

你必须使用jquery的Id选择器

$("#formId")

而不是您使用的类“表单”。

您的简化 HTML:

<form id="form1">                 
<input type="submit" id="submit1"/>
</form>

<form id="form2">
<input type="submit" id="submit2"/>
</form>

简化的 JS:

var form1 = $('#form1');
var submit1 = $('#submit1');
form1.submit(function(e) {
alert('hey1');
// prevent default action
e.preventDefault();
// send ajax request
});

var form2 = $('#form2');
var submit2 = $('#submit2');
form2.submit(function(e) {
alert('hey2');
e.preventDefault();
});

JSFIDDLE 中的结果:http://jsfiddle.net/jzb2hn9j/

关于javascript - 两个 HTML 表单冲突,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27275575/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com