Amra
Amra

Reputation: 25268

JQuery add id and values to textbox when adding row

I need to add a values (if anything coming into function when form is loading) and a sequential id (e.g. id="textbox_1" - id="textbox_2" etc..) to the textboxes inside an added row with jquery.

To add id it would be as example for each time the function gets called, it would increase by one the end of the id of the textbox (e.g. id="textbox1", next id="textbox2", etc...).

Also, notice that the first row does not have an id, How can I fix this?

To add values into textboxes, it would need to be, text1 going into class=textbox1

The code I currently have is.

Thanks to everyone.

<html>
<head>
<script type="text/javascript">         
function createNewRow (text1,text2){
 $('#tblOtherParties > tbody').append('<tr><td>
    <input type="text" class="title1" value=""/>
   </td><td>
    <input type="text" class="title2"  value=""/>
   </td><td>
     <input type="button" class="btnDeleteOther" value="X"/>
  </td></tr>');

}

$(document).ready(function(){
  $(".btnDeleteOther").live("click", function(){
  $(this).closest('tr').not(':only-child').remove();
});

$('#btnAddOther').click(function(){
  createNewRow('hello','you');
  });

});

</script>
</head>
<body>
  <table style="float:left" id="tblOtherParties">
   <thead>
    <tr>
      <th>Title1</th>
      <th>Title2</th>
      <th>
    <input type="button" id="btnAddOther" value="Add"/>
      </th>
    </tr>
   </thead>
   <tbody>
    <tr>
     <td>
      <input type="text" class="title1"/>
     </td>
     <td>
       <input type="text" class="title2"/>
     </td>
     <td>
      <input type="button" class="btnDeleteOther" value="X"/>
     </td>
    </tr>
   </tbody>
 </table>
</body>
</html>

Upvotes: 0

Views: 2434

Answers (2)

Seaux
Seaux

Reputation: 3517

Cesar, You can create a global variable var counter = 0; And increment this variable each time and item is created and then include this inside your createNewRow function, like so:

  
function createNewRow (text1,text2){
 var first = counter++;
 var second = counter++;
 $('#tblOtherParties > tbody').append('<tr><td>
    <input type="text" id="textbox_'+first+'" class="title1" value="'+text1+'"/>
   </td><td>
   <input type="text" id="textbox_'+second+'" class="title2"  value="'+text2+'"/>
   </td><td>
     <input type="button" class="btnDeleteOther" value="X"/>
  </td></tr>');
}

Note also that I have the text1 and text2 added in the values. :-) Hope this helps

Upvotes: 1

sorpigal
sorpigal

Reputation: 26116

It's not clear what you're asking, but...

You can count the number of existing rows with this

var i = $('#tblOtherParties>tbody>tr').length;

And then use i+1 wherever you need your sequential ID.

Upvotes: 0

Related Questions