我目前在一个页面上有两个表单,一个更新表单和一个添加表单,我想要做的是提交任一表单,拉取该表单的 id 以及操作,验证特定表单,然后加载返回从网络服务器。
我通过专门使用每个表单的 id 让它工作,但是 js 代码重复了两次,id 更喜欢它更动态一点。
<script src="assets/js/jquery-1.8.2.js"></script>
<script src="assets/js/bootstrap.js"></script>
<script src="assets/js/jquery.validate.js"></script>
<div id="myTabContent" class="tab-content">
<div class="tab-pane active" id="update">
<form action="php/update_level.php" method="post" id="form1">
<h2>Update Level</h2>
<label>Select Bag Level</label>
<select id="target" name="levelSelect"> <option selected>Select</option>
<?php
foreach($result as $row)
{?>
<option><?php echo $row['Level'] ?></option>
<?php
}
?>
</select>
<div id="upForm">
</div>
<div class="message">
</div>
</form>
</div>
<div class="tab-pane" id="addNew">
<form action="php/add_level.php" id="form2">
<h2>New Level</h2>
<label>Level</label>
<input class="required" maxlength="10" minlenght="1" type="text" name="level" placeholder="Level">
<label>Description</label>
<textarea class="required" name="description" rows="3" placeholder="Description of level type"></textarea>
</br>
<div class="message">
</div>
<div class="form-actions">
<button id="inFormSub" type="submit" class="btn btn-large btn-primary">Submit</button>
</div>
</form>
</div>
</div>
JS:
$('form').submit(function(e){
e.preventDefault();
var id=$(this).attr('id');
var action=$(this).attr('action');
console.log(action + ' ' + id); //works outputs update_bag.php form1 on submit of form1
//add_bag.php form2 on submit of form2
$(id).validate({
submitHandler: function() {
console.log(action + ' ' + id); //doesnt work
$(id).find('div.message').load(action, $(id).serializeArray());
}
});
有效的 JS
$('#form1').validate({
submitHandler: function() {
var action = $('#form1').attr('action');
console.log(action + ' validate1');
$('#form2').find('div.message').load(action, $('#form1').serializeArray());
}
});
$('#form2').validate({
submitHandler: function() {
var action = $('#form2').attr('action');
console.log(action + ' validate2');
$('#form2').find('div.message').load(action, $('#form2').serializeArray());
}
});
我对 JS 和 Jquery 的了解充其量是很少的,我可能正盯着解决方案