【问题标题】:Dynamic HTML form with jQuery - Then later editing the data使用 jQuery 的动态 HTML 表单 - 然后稍后编辑数据
【发布时间】:2013-11-23 13:08:14
【问题描述】:

嗯,

我已经尝试解决这个问题已经有一段时间了,但完全没有运气。

现在,我有一个带有 jQ​​uery 的 HTML 表单,可以动态添加或删除费用。然后将此信息放入 php 数组并存储到数据库中。

我想要的是能够从数据库中提取该数组,对条目进行计数,并将它们放入 HTML 表单上正确数量的输入框中。我仍然希望在这里使用 jQuery,因为我希望用户能够在这个“编辑”阶段添加或删除费用。

如果感到困惑,请提出问题。

jQuery v

<script type="text/javascript">
    $(document).ready(function() {
        $('#btnAdd').click(function() {
            var num     = $('.clonedInput').length; // how many "duplicatable" input fields we currently have
            var newNum  = new Number(num + 1);      // the numeric ID of the new input field being added

            // create the new element via clone(), and manipulate it's ID using newNum value
            var newElem = $('#input' + num).clone().attr('id', 'input' + newNum);

            // manipulate the name/id values of the input inside the new element
            newElem.children(':first').attr('id', 'name' + newNum)

            // insert the new element after the last "duplicatable" input field
            $('#input' + num).after(newElem);
            $('input[name="name[]"]:last').val(null);

            // enable the "remove" button
            $('#btnDel').attr('disabled','');

        });

        $('#btnDel').click(function() {
            var num = $('.clonedInput').length; // how many "duplicatable" input fields we currently have
            $('#input' + num).remove();     // remove the last element

            // enable the "add" button
            $('#btnAdd').attr('disabled','');

            // if only one element remains, disable the "remove" button
            if (num-1 == 1)
                $('#btnDel').attr('disabled','disabled');
        });

        $('#btnDel').attr('disabled','disabled');
    });
</script>

HTML v

<tr id="input1" style="margin-bottom:4px;" class="clonedInput">
        <td><span style="color:#00CD00;">Charge:</span></td>
        <td><input type="text" name="name[]" size="35"/></td>
      </tr>
      <tr>
        <td><input type="button" id="btnAdd" value="Add Another Charge" /></td>
        <td><input type="button" id="btnDel" value="Remove Charge" /></td>
      </tr>

另外,如果您看到我可以在我的代码中使用的任何改进,请提出建议。我对使用 jQuery 很陌生,我想尽可能多地学习。

【问题讨论】:

    标签: php jquery html forms dynamic


    【解决方案1】:

    虽然可以在 jquery 中重新填充产品,但我会尝试在标签中使用 php 重新填充它们。这纯粹是为了简化开发。使用 jquery 填充需要获取 json 提要中的元素,并且基于此,您可以重新使用必须重新填充的相同代码,但这次,在文本框中使用值。

    【讨论】:

    • 确切地说,我该怎么做呢?我不介意它是如何填充的,我只想在填充后能够添加/删除输入框。
    • 好吧,既然我希望表单仍然是动态的,我想我们必须使用 jQuery 进行填充。
    • 我建议在检索阶段通过 php 填充。您可以使用 $(this).closest('tr') 链接表以通过 jquery 删除预填充的行并删除该行。我希望我让事情变得更清楚,而不是让事情变得更糟。
    猜你喜欢
    • 1970-01-01
    • 2013-08-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-06
    相关资源
    最近更新 更多