多表单验证:有效时放置$ ajax的位置?

时间:2014-01-30 22:30:17

标签: javascript jquery validation

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

1 个答案:

答案 0 :(得分:0)

您的foo活动中未定义

submit。需要添加以下字符串:

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