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

标签 javascript php jquery ajax forms

我使用 php.ini 在 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>

问题是,每个按钮都会提交页面上绘制的第一个表单。我该如何做到这一点,以便将每个按钮设置为每个表单,同时记住正在绘制的表单数量未知?

最佳答案

我想您应该澄清要使用 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.

关于javascript - 使用 jquery/ajax 提交循环表单?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39258070/

相关文章:

javascript - 解除绑定(bind) jQuery 插件中的特定滚动事件

javascript - React - 带 Bootstrap 的全屏模式

javascript - mongodb删除旧聊天记录

javascript - Jquery如何改变选择<option>框中的一个单词的颜色

javascript - 如何在新窗口中打开视频

php - 如何在 PHP 中复制 MySQL 的 aes-256-cbc

php - CodeIgniter:将数据从数据库导出到 excel 并下载

javascript - 如何使用 jquery 克隆多个 html 输入字段

javascript - 将 localStorage 数据更改为 jQuery 中的 html 列表标记

javascript - 遍历Html中的id