我有两种形式相互冲突 我想在“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 code:
<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>
答案 0 :(得分:2)
您必须使用jquery的Id选择器
$(&#34;#formId&#34)
而不是班级&#39;表格&#39;你用的。
您的简化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/
答案 1 :(得分:1)
给每个表单一个像这样的id
<form id="firstForm" method="post">
..... form data
</form>
<form id="secondForm" method="post">
..... form data
</form>
然后选择表格
var formOne = $("#firstForm"),
formTwo = $("#secondForm");