jquery - 使用 jquery 从输入字段更改名称的一部分
问题描述
我试图将行动态添加到表中。我已经克隆了最后添加的行。在每个新行上,输入字段的名称应该用一个数字重命名+1
。为此,我想重命名输入字段,但我没有这样做。
Original row
<input type="text" name="myfiels[0]" value="mytext">
First clone row
<input type="text" name="myfiels[1]" value="mytext">
Second clone row
<input type="text" name="myfiels[]" value="mytext">
...
$trNew.find('[name]').each(function () {
var num = this.name.replace(/\D/g, '');
if (!num) {num = 0;}
// Remove numbers by first regexp
// increment number
//this.name = this.name.replace(/\d/g, '') + (1 + parseInt(num, 10));
this.name.replace(/[.+]/,"["+(1 + parseInt(num, 10))+"]");
});
我认为regex
是错误的。
解决方案
您可以使用一些变量 ie :count
它将保存下一个要添加的值name
,当您循环遍历每个输入时,您可以获得名称input
并将其替换为新名称 ie :name+"["+count+"]"
然后将计数增加1
.
演示代码:
var count = 0;//delcare this
$("div").find('input').each(function() {
var name = $(this).attr("name");//get name of input field
$(this).attr("name", name +"[" + count + "]");//add new name
count++;//increment
});
function namess() {
$("div").find('input').each(function() {
console.log($(this).attr("name"));
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Original row
<div>
<input type="text" name="myfiels" value="mytext"> First clone row
<input type="text" name="myfiels" value="mytext"> Second clone row
<input type="text" name="myfiels" value="mytext"> ...
</div>
<button onclick="namess()">Click me to get names</button>
推荐阅读
- arrays - 两个矩阵上的非成对距离计算,作为整体矩阵到矩阵的接近度计算
- python - 如何在 Pythonista3 中使用 asyncio?
- reactjs - 您可以订阅 Zusand 的某个州的某些部分吗?
- python - 在 python 休息请求中收到不完整的响应
- javascript - JavaScript - 使用函数、子字符串、大小正确输入验证?
- selenium - 如何使用 Selenium Webdriver 捕获特定元素而不是整个页面的屏幕截图?我尝试了已经可用的答案
- node.js - 无法保存来自猫鼬查询的数据
- python - drawcontours 区域的图像处理
- javascript - React 播放器视频在播放时不会停止
- python-3.x - pycurl登录错误请求?