使用jquery / ajax提交循环表单?

时间:2016-08-31 20:01:57

标签: javascript php jquery ajax forms

我使用php在foreach循环中创建表单。

每个表格都有一个增加的lpformnum

<form lpformnum="1"><button class="update" /></form>
<form lpformnum="2"><button class="update" /></form>
<form lpformnum="3"><button class="update" /></form>
etc.

我使用jquery / ajax来阻止表单的默认操作,以便我可以通过ajax提交表单。

<script>
    $(document).ready(function(){        
        $('.alert').on('click', 'button[class=update]', function(e) {
         e.preventDefault();
         e.stopPropagation();
            var checkValues = $("#update").val();
            var checkCred = $("#ucredits").val();
            var checkPost = $("textarea").text();
            var checkType = $("i").text();
            $.ajax({
                type: "POST",
                url: "update_social_cred.php",
                data: { id: checkValues, credits: checkCred, text: checkPost, type: checkType  },
                success:function(result) {
                 alert (checkCred);
                }
            });
        });
    });
</script>

问题是,每个按钮都会提交页面上绘制的第一个表单。我如何做到这一点,所以每个按钮都设置为每个表格,记住有不明数量的表格被绘制?

1 个答案:

答案 0 :(得分:1)

我想您应该使用find()方法澄清要提交的数据。

$('.alert').on('click', 'button[class=update]', function(e) {
    e.preventDefault();
    e.stopPropagation();

    // find parent form of a button
    var form = $(this).closest( "form" );

    // I suppose these are unique fields.
    var checkValues = $("#update").val();
    var checkCred = $("#ucredits").val();
    var checkPost = $("textarea").text();
    // if they are not you should use classes instead:
    // something like:
    // var checkCred = form.find(".ucredits").val();

    // find values in a `form` with `find` method
    var checkType = form.find("i").text();

    // pass your data to ajax.