2

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?

Gopesh
  • 3,882
  • 11
  • 37
  • 52

3 Answers3

2

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.

Sean Johnson
  • 5,567
  • 2
  • 17
  • 22
0

You can change the id attribute by using:

$(selector).attr('id', 'new-id-here');
davey
  • 1,801
  • 2
  • 17
  • 22
0

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

Community
  • 1
  • 1
Scott
  • 2,753
  • 1
  • 24
  • 31
  • Thanks for the reply.. i need to cahnge the id of each textbox – Gopesh Oct 09 '13 at 07:48
  • Ah, gotcha. Do you really need to use IDs in this case, then? Johan's comment to your post about using a class instead might be a better idea unless you *absolutely* need unique IDs on each textfield. – Scott Oct 09 '13 at 07:52