gpt4 book ai didi

javascript - 多表单验证: where to put $ajax when valid?

转载 作者:行者123 更新时间:2023-11-28 08:33:57 26 4
gpt4 key购买 nike

我在一个页面上有多个表单,我正在尝试使用 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>

最佳答案

foo 在您的 submit 事件中未定义。需要添加以下字符串:

$('.form').on('submit', function(){
var foo = $('select', this).val();
...
});

关于javascript - 多表单验证: where to put $ajax when valid?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21468815/

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