使用 jQuery 的动态 HTML 表单 - 稍后编辑数据


Dynamic HTML form with jQuery - Then later editing the data

嗯,

我一直试图解决这个问题很长一段时间,但绝对没有运气。

现在,我有一个带有jQuery的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>

网页 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相当陌生,我想尽可能多地学习。

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