virender
virender

Reputation: 27

adding n removing row in table with unique id of elements

here's a demo table

<table id="table1">
<tr>
<td><label>name</label><input type="text" id= "name1"/></td>
<td><label>age</label><input type="text" id= "age1"/></td>
<td><input type="button" id= "addRow"style="background-image:url("images/addicon.png");"/></td>
</tr>

and jquery code m trying is

 $("#addRow").live("click", function (e, index) {
 var val = ("#table1 tr").length();
 val++;
    $('#table1  tbody > tr:last').after('<tr><td><label>name</label><input type="text" id= "name"'+val+'/></td><td><label>age</label><input type="text" id= "age"'+val+'/></td><td><input type="button" id= "addRow"style="background-image:url("images/addicon.png");"/></td><td><input type=button  id="deleteRow" style="background-image:url("images/removeicon.png");"></td>');
  });
  $("#deleteRow").live("click",function(e,index){
     $(this).parent().closest("tr").remove();
  });

Now problem comes when somebody add a row 2 times and delete a row i.e val will be name2, name3 suppose name2 is deleted then again adding row no. of rows is 2 so val++ result in 3 and new row will have name3 as id, this is creating problem for me. What actually i want is, I should maintain the row count 1 2 3 ... like this irrespective what row is deleted. Can anyone help me out with this, I have gone through loads of tutorial but none of them have maintained a uniform rowcount that's y i have put up this question.

Upvotes: 1

Views: 245

Answers (1)

Explosion Pills
Explosion Pills

Reputation: 191769

You can use input names like name[] to have an array of values in the form. This is easier than using things like name1, name2, etc. If your concern is the labels, you can wrap an input in a label and skip the for, like so:

<label>String: <input></label>

Clicking String: focuses the input.

If you want to stick with what you have, just store val one scope outside of .click and increment it every time. Don't rely on the length.


By the way, you should also switch from .live to .on assuming it's available.

Upvotes: 1

Related Questions