[英]Assign id to Input element which has only name attribute
I have set of table rows, each row has input elements defined with only name[] attribute, 我有一组表行,每行都有仅用name []属性定义的输入元素,
<tr id="1">
<td><input name="billdate[]" required="required" class="form-control" placeholder="DD/MM/YYYY"></td>
<td><input class="form-control" name="amt[]" required="required" value="0" type="text"></td>
<td><input name="gst[]" class="form-control" value="0" required="required" type="text"></td>
<td><input name="netamt[]" class="form-control" required="required" value="0" type="text"></td>
<td><input name="glcode[]" class="form-control" required="required" value="" type="text"></td>
</tr>
I have added JavaScript code to clone table row, code written below 我添加了JavaScript代码来克隆表行,代码如下
var row = document.getElementById("1"); // find row to copy
var table = document.getElementById("asd"); // find table to append to
var clone = row.cloneNode(true); // copy children too
clone.id = document.getElementById("setid").value; // change id or other attributes/contents
table.appendChild(clone);
cloning is working fine, but the problem is that I want to assign unique ids to each input element. 克隆工作正常,但问题是我想为每个输入元素分配唯一的ID。 Is there any easy way to do this?
有没有简单的方法可以做到这一点? I tried several ways to add but did not succeeded.
我尝试了几种添加方法,但没有成功。
function guid() {
function s4() {
return Math.floor((1 + Math.random()) * 0x10000)
.toString(16)
.substring(1);
}
return s4() + s4() + '-' + s4() + '-' + s4() + '-' +
s4() + '-' + s4() + s4() + s4();
}
clone.id = guid()
It's not a true guid, but it should work fine. 这不是真正的向导,但应该可以正常工作。
Create GUID / UUID in JavaScript? 在JavaScript中创建GUID / UUID?
Not sure if this is what your looking for. 不确定这是否是您的寻找。 But looping through childnodes and getting input element then assigning ID seems to do the trick.
但是,遍历子节点并获取输入元素然后分配ID似乎可以解决问题。
var row = document.getElementById("1"); // find row to copy
var table = document.getElementById("asd"); // find table to append to
var clone = row.cloneNode(true); // copy children too
clone.id = 'blue';//document.getElementById("setid").value;'' // change id or other attributes/contents
var children = clone.children
for( var t = 0 ; t < children.length; t++ ){
children[t].children[0].id = 'id-'+t;
}
//Debugging
console.dir( clone );
table.appendChild(clone);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.