Reputation: 3950
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.
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?
Upvotes: 2
Views: 11865
Reputation: 5607
If 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.
Upvotes: 2
Reputation: 2793
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 );
});
Upvotes: 0
Reputation: 1791
You can change the id attribute by using:
$(selector).attr('id', 'new-id-here');
Upvotes: 0