首页 > 解决方案 > 如何自动将数字添加到克隆输入的文本名称

问题描述

我遇到了一个问题,我已经尝试解决了几个小时......我想更改我的自动克隆输入的名称。

这是我的 HTML 代码:

 <form id="dodawanie" action="" method="post">
     <div class="formularz">
         <fieldset>
             <input type="number" id="indeks" name="indeks" class="pozycja">Indeks
             <input type="text" id="tytul" name="tytul" class="pozycja">Tytuł
             <input type="text" id="opis" name="opis" class="pozycja">Opis
             <input type="text" id="gatunki" name="gatunki" class="pozycja">Gatunki
             <input type="text" id="tagi" name="tagi" class="pozycja">Tagi
             <input type="text" id="rok" name="rok" class="pozycja">Rok
             <input type="text" id="pv" name="pv" class="pozycja">PV
             <input type="text" id="obrazki" name="obrazki" class="pozycja">Obrazki
             <input type="text" id="odcinki" name="odcinki" class="pozycja">Odcinki
        </fieldset>
    </div>
    <input type="submit" name="dodaj">
    <button type="button">+</button>
 </form>

这是我的 jQuery 脚本:

$(document).ready(function(){
    var count = 1;
    $("button").click(function(){
        var kopiuj = $(".formularz").first().clone(); 
        var current_name = $('[name]');
        current_name.each(function(){
            $currname = $(this).attr('name');
            $('input').each(function(){
                $(kopiuj).find('.pozycja').attr('name', ""+$currname+"["+count+"]");
            });
        });
        $(".formularz").last().after(kopiuj);
        count++;
    });
});

如何将数字添加到name克隆输入的属性?

标签: jqueryhtml

解决方案


您的脚本有点过于复杂,但似乎可以工作(不是吗?)。检查下面的简化版本:

$(document).ready(function(){
    $("button").click(function(){
        var formularz = $(".formularz");
        var kopiuj = formularz.first().clone();
        var liczba = formularz.length;
        kopiuj.find('.pozycja[name]').each(function(){
            $(this).attr('name', this.name + '[' + liczba + ']');
        });
        formularz.last().after(kopiuj);
    });
});

尝试工作演示: https ://jsfiddle.net/tvcsubaf/

请注意,以这种方式将表单数据发送到后端可能不是一个好主意。您应该从克隆的输入值(即indeks[])创建数组或根据方案命名它们:indeks-1indeks-2等。


如果您决定添加[0]到基本name属性,然后在下一组字段中增加此数字,您可以使用以下脚本:

$(document).ready(function(){
    $("button").click(function(){
        var last = $(".formularz:last");
        last.clone().insertAfter(last).find('.pozycja[name]').each(function(){
            $(this).attr('name', this.name.replace(/(\d+)/, function(){
                return arguments[1]*1+1;
            }));
        });
    });
});

工作演示:https ://jsfiddle.net/9chwkx82/


推荐阅读