admin管理员组文章数量:1423806
I have a form in which i need to dynamically add certain row on button click.Html is added dynamically on click, but i need to change the id value for dynamically added elements.
Demo
Js Code
$(function () {
$('.click').on('click', function () {
$('#mytable tbody tr').clone(true).insertAfter('#mytable tbody');
});
});
What i need is <input type="text" id="name_1" />
adding an increment value to id attribute for each textbox.
Any ideas?
I have a form in which i need to dynamically add certain row on button click.Html is added dynamically on click, but i need to change the id value for dynamically added elements.
Demo
Js Code
$(function () {
$('.click').on('click', function () {
$('#mytable tbody tr').clone(true).insertAfter('#mytable tbody');
});
});
What i need is <input type="text" id="name_1" />
adding an increment value to id attribute for each textbox.
Any ideas?
- 1 Why not use a class instead? – Johan Commented Oct 9, 2013 at 7:42
- .. right and eventually set the id on the first mon ancestor – Stphane Commented Oct 9, 2013 at 7:55
3 Answers
Reset to default 2If you want to change the ID of each textbox as you add it, try this:
// Code goes here
$(function(){
var unique_id=0
$('.click').on('click',function(){
unique_id++
$('#mytable tbody tr').clone(true).insertAfter('#mytable tbody')
.find("input")
.each(function(){
$(this).attr("id",$(this).attr("id")+"_"+(unique_id))
})
});
});
Forked your Plunker: http://plnkr.co/edit/R6qvaZ2m2Kt2DEGL3SWF?p=preview
Note: This form data will not submit properly, as the fields do not have any name values. If you plan on allowing the form to be submitted naturally, rather than having to rely on JS, you could always try the following:
<input type="text" name="name[]" />
<input type="text" name="age[]" />
<input type="text" name="salary[]" />
... in which case you would be perfectly okay with duplicating the input fields, and not having to give each one a unique id.
You can change the id attribute by using:
$(selector).attr('id', 'new-id-here');
I take it you need to change the ID on a cloned element before inserting it? You might try the answer posted on this potentially-similar question: How to JQuery clone() and change id
var c = 0;
$("button").on('click',function(){
var klon = $( '#id'+ c );
klon.clone().attr('id', 'id'+(++c) ).insertAfter( klon );
});
jsfiddle here
本文标签: javascriptDynamically change id attribute valueStack Overflow
版权声明:本文标题:javascript - Dynamically change id attribute value - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744734178a2622223.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论