jquery - 如何自动将数字添加到克隆输入的文本名称
问题描述
我遇到了一个问题,我已经尝试解决了几个小时......我想更改我的自动克隆输入的名称。
这是我的 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
克隆输入的属性?
解决方案
您的脚本有点过于复杂,但似乎可以工作(不是吗?)。检查下面的简化版本:
$(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-1
,indeks-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;
}));
});
});
});
推荐阅读
- mysql - 如何在 Mysql 语句中添加选择性行
- javascript - 在 Angular 网页中模拟文本用户输入
- windows - ETW 意外跟踪事件 254?
- blockchain - 可铸币 ERC721 的 CappedCrowdsale
- html - xlink 引用的 svg 数据的位置?
- javascript - TypeError:无法使用 ReactJs 读取未定义的属性“地图”
- bluetooth-lowenergy - BLE广播帧和BLE信标帧之间有区别吗
- python - 当我训练具有多个网络的类似 GAN 的图时,如何确保 tf.control_dependencies() 的正确行为?
- android - Android Studio中连接两列并更新到另一列的正确语法是什么
- xcode - Xcode 10 Beta CompileSwiftSources 失败