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?

Share Improve this question edited Oct 9, 2013 at 7:47 Gopesh asked Oct 9, 2013 at 7:40 GopeshGopesh 3,95011 gold badges39 silver badges53 bronze badges 2
  • 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
Add a ment  | 

3 Answers 3

Reset to default 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.

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