我在頁面上有多個表單,我試圖用jQuery來驗證它們。驗證部分正在工作,但是,如果表單有效,我無法弄清楚應該在哪裏放置ajax。
更新:我不知道有多少表格會有這些動態生成。
<p><a href="">reload</a></p>
<div id="messages">
<div id="message">
<ul></ul>
</div>
</div>
<form action="#" method="post" class="form">
<select name="foo" class="required">
<option value="">Select...</option>
<option value="foo">Foo</option>
</select>
<input type="text" name="bar" class="required">
<input type="submit" value="submit">
</form>
<form action="#" method="post" class="form">
<select name="foo" class="required">
<option value="">Select...</option>
<option value="snafoo">Snafoo</option>
</select>
<input type="text" name="bar" class="required">
<input type="submit" value="submit">
</form>
<script src="//code.jquery.com/jquery.js"></script>
<script src="//ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.js"></script>
<script>
$('.form').each(function() {
$(this).validate({
submitHandler:function(form) {
var foo = $(form).find('select[name=foo]').val();
var bar = $(form).find('input[name=bar]').val();
form.submit();
},
rules: {
foo: {
required: true
},
bar: {
required: true
}
},
messages: {
foo: {
required: 'Please select a foo'
},
bar: {
required: 'Please enter a bar'
}
},
errorContainer: $('#messages'),
errorLabelContainer: $('#messages ul'),
wrapper: 'li',
// callback functions to work with bootstrap
highlight:function(element) {
$(element).closest('.form-group').addClass('has-error');
},
unhighlight:function(element) {
$(element).closest('.form-group').removeClass('has-error');
}
});
});
// if the form is valid, do some ajax...
$('.form').on('submit', function(){
if($(this).valid()){
// testing...
alert(foo);
$.ajax({
type: 'POST',
url: 'script.php',
data: 'foo=' + foo,
cache: false,
success: function(data){
// do stuff...
}
});
}
return false;
});
</script>
現在的地方出了什麼問題? – Oleg
@oleg:它不起作用。沒有警報,沒有什麼... – timgavin
沒有警報,因爲'foo'是未定義的。只是看看開發者控制檯有時;-) – Oleg