-1

I have a button each time it is clicked, a new select input will be added. But I want the id and name of the select changed as well.My codes was:

<section>
  <div class="container">
   <select id="myId_1" name="myName_1">
     <option value="1">1</option>
     <option value="2">2</option>
   </select>
  </div>
</section>
<button type="button" id="myBtn">add</button>

$(document).ready(function () {
    $('#myBtn').click(function(){
      var addEvent = $('.container').html();
      var addEventCell = $('<div class="container">'+addEvent+'</div>');
      $('section').append(addEventCell);
    });
  });

But my code just duplicates the id and name of select. I want it to change to myId_2, myName_2,myId_3,myName_3 and so on.

I am new to javascript. It could be easy to you guys. Thanks for help !

Alastair Pitts
  • 19,423
  • 9
  • 68
  • 97
Yujun Wu
  • 2,992
  • 11
  • 40
  • 56
  • 1
    check this http://stackoverflow.com/questions/3416227/create-dynamic-div-with-unique-ids-jquery it might help you achieve what you are trying to. – TRR Jul 13 '12 at 06:34

2 Answers2

0
  $(document).ready(function () {
    $('#myBtn').click(function(){
      var addEvent = $('.container:last').html();
      var addEventCell = $('<div class="container">'+addEvent+'</div>');
      var select = $('select', addEventCell);
      var oldId = select.attr('id');
      var newId = oldId.split('_')[0] + '_' + (parseInt(oldId.split('_')[1]) + 1);
      select.attr('id', newId).attr('name', newId);
      $('section').append(addEventCell);
    });
  });​

http://jsfiddle.net/QVYhu/

odupont
  • 1,946
  • 13
  • 16
0

this is the link for JSFiddle working here. It may be useful for you

$(document).ready(function () {
    $('#myBtn').click(function(){
      var addEvent = $('.container').html();

      var selectid = $('section :last-child select').attr('id'); 
      var selectname = $('section :last-child select').attr('name'); 

      var tempId = parseInt(selectid.split('_')[1])+1; 
      var tempName = parseInt(selectname.split('_')[1])+1; 
      var addEventCell = $('<div class="container">'+addEvent+'</div>');

      var newId =  selectid.split('_')[0]+"_"+tempId; 
      var newName = selectname.split('_')[0]+"_"+tempName ;

      var select = $('select', addEventCell);
      select.attr('id', newId).attr('name', newName);      

      $('section').append(addEventCell);
    });
  });​
muthu
  • 5,381
  • 2
  • 33
  • 41