在具有多个表单的页面中提交表单时从表单获取信息

时间:2014-01-25 17:10:26

标签: jquery html forms

我有一个包含多个表单的HTML页面。代码如下所示:

<form method="post" action="#">
    Hour: <select name="hour_id">...</select>
    Class: <select name="class_id">...</select>
    Teacher: <select name="teacher_id">...</select>
    <a class="go_to_class">Go to class</a>
</form>

<form method="post" action="#">
    Hour: <select name="hour_id">...</select>
    Class: <select name="class_id">...</select>
    Teacher: <select name="teacher_id">...</select>
    <a class="go_to_class">Go to class</a>
</form>

<form method="post" action="#">
    Hour: <select name="hour_id">...</select>
    Class: <select name="class_id">...</select>
    Teacher: <select name="teacher_id">...</select>
    <a class="go_to_class">Go to class</a>
</form>

[...]

<form method="post" action="#">
    Hour: <select name="hour_id">...</select>
    Class: <select name="class_id">...</select>
    Teacher: <select name="teacher_id">...</select>
    <a class="go_to_class">Go to class</a>
</form>

我想做的是编写一个jQuery代码,允许我提交任何表单并通过POST将这些信息发送到AJAX脚本。此外,我需要执行一些验证,以确保用户已选择他想要提交的表格中的“小时”,“班级”和“老师”的值。

就jQuery而言,我知道如何序列化表单值并将其发送到脚本,但我不知道如何获取值以执行验证。

$(document).ready(function() { 
    $('.go_to_class').click(function(e) {
        e.preventDefault();
        $(this).closest('form').submit(function() {
            var values = $(this).serialize();
        });
    });
});

感谢任何帮助。

谢谢!

1 个答案:

答案 0 :(得分:0)

您可以使用.serializeArray()来获取所有输入字段

$(document).ready(function() { 

    $('.go_to_class').click(function(e) {
        e.preventDefault();
        $(this).closest('form').trigger('submit');
    });

    $('form').submit(function(e) {
        e.preventDefault();
        var fields = $( this ).serializeArray();
        $.each(fields, function(i,field){
            console.log(field.name,field.value);
        });
    });

});