【问题标题】:Map dynamic array of checkboxes without index映射没有索引的复选框的动态数组
【发布时间】:2015-02-06 01:58:50
【问题描述】:

此问题进一步建立在此处提出的问题之上:How to map dynamic array of input fields

我有一组动态的行,每个行都有自己的输入字段。这些行可以动态添加到 DOM,所以我必须使用没有索引的输入数组(例如 fieldname[] 而不是 fieldname[1] 等)。

当我在这些行中使用复选框时会出现问题。由于未选中复选框时未提交复选框,因此我无法知道哪个提交的复选框属于哪个行值。

我的表单示例:

<form>
<div class="row">
     <input type="text" name="product[]">
     <input type="text" name="qty[]"> 
     <input type="checkbox" name="projectline[]"> 
</div>
<div class="row">
    <input type="text" name="product[]">
    <input type="text" name="qty[]">
    <input type="checkbox" name="projectline[]"> 
</div>
<div class="row">
     <input type="text" name="product[]">
     <input type="text" name="qty[]">
     <input type="checkbox" name="projectline[]"> 
</div>
</form>

我在这里找到了类似问题的答案:php array of checkboxes,但答案显然只适用于具有索引的数组。

这里最好的方法是什么?

编辑:

我还会在服务器端检查表单是否有错误,如果出现错误则将其重定向回来,因此我需要能够根据提交的值“重建”表单。

【问题讨论】:

  • 是否有可能持续计算您拥有的数量并在放入时为其分配索引?
  • 我同意 QPaysTaxes。这似乎是最有意义的。
  • 我可能可以通过 javascript 来解决这个问题,但希望有一个更优雅的解决方案。
  • 给他们一个价值...&lt;input type="checkbox" name="projectline[]" value="&lt;index, id, ...&gt;" /&gt;

标签: php jquery html dom


【解决方案1】:

我见过的一个技巧是在每个提交相同字段且值为 0 的复选框之前放置一个隐藏字段。这样,如果您选中复选框,它将用复选框值覆盖 0 值,但如果你不这样做,你会得到一个 0 表示未选中,而不是你的数据中没有任何内容。

cmets 给出的保持索引总数的答案也可能有效,但根据修改 DOM 的方式和时间而定,这会有点复杂。

【讨论】:

  • 我遇到了这个解决方案,但在这种情况下它不起作用,因为我使用的是非索引数组。当复选框被选中时,这两个字段都被提交。
【解决方案2】:

我最终为每一行分配了一个索引号,每次添加一行时都会生成一个新的随机 id。我使用 jQuery 进行克隆函数和事件绑定。

以下是我的完整解决方案。

这是我的原始表格:

<form>
<div class="row">
 <input type="text" name="product[0]">
 <input type="text" name="qty[0]"> 
 <input type="checkbox" name="projectline[0]"> 
</div>
</form>

我有一个模板行,用于克隆:

<div id="templaterow">
 <input type="text" name="product[%%index%%]">
 <input type="text" name="qty[%%index%%]">
 <input type="checkbox" name="projectline[%%index%%]"> 
</div>

克隆行的按钮:

<button id="addrow" value="add new row"/>

还有一个绑定到按钮的函数:

$('#addrow').on('click',function()
{
    //template row is cloned and given the right attributes:
    var clone = $('#templaterow').clone(true, true);
    $('.row').last().after(clone);
    clone.addClass('row').removeAttr('id');

    // the %%index%% placeholder is replaced by a random index number between 100 and 9999999
    clone.html(function (index, html) {
        var rndIndex = Math.floor((Math.random() * 9999999) + 100);
        return html.replace(new RegExp('%%index%%','g'),rndIndex);
    });
});

【讨论】:

    猜你喜欢
    • 2012-03-06
    • 1970-01-01
    • 2021-10-23
    • 1970-01-01
    • 2019-08-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-14
    相关资源
    最近更新 更多