Link to home
Start Free TrialLog in
Avatar of Web_Sight
Web_Sight

asked on

Dynamic form element deletion using jQuery

I have a dynamic form using jQuery. Rows are created based on the values from drop down(please check image) . Each row is created with a <p> tag and unique id. If I delete a row in between the id appended to all those rows after the deleted row should be decremented by 1.
For ex: if we have 1 to 10 rows each row identified as 1,2,3, .....10. If I delete 5th row then there should be no 10th row and series would be 1,2,3....9.
The values of all the remaining rows should be preserved.  How can I do this using jQuery?
problem.jpg
Avatar of lunadl
lunadl
Flag of United States of America image

Write a loop on delete that reduces the id of all the <p> if it is a number greated than the id of the deleted row. Here is an easy function to test if you are looking at the right p tags and to avoid any errors, http://stackoverflow.com/questions/18082/validate-numbers-in-javascript-isnumeric .
 Get the element id on delete.Your loop will be on row delete and checks all the p tag ids. Then write an if statement in the loop to see if the ids are greater than what was deleted, if so, reduce the id by one, otherwise skip it.
Avatar of Web_Sight
Web_Sight

ASKER

Thanks for your comment.
Still, how can I change the element id. Is there any function to change element id?
Avatar of David S.
In jQuery you'd use the attr() method: http://docs.jquery.com/Attributes/attr#keyvalue

Try the following code.

P.S. Is there a particular reason why you chose to use <p>s?
$('#parentId p').attr('id',function(idx){ 
  // change "parentId" and "idPrefix" as needed
  return 'idPrefix'+(idx+1);  // because indexes start at 0 and IDs start at 1
});

Open in new window

Thanks for your valuable comments.
Now I can rename id and attribute.But how can rename event functions with paramenter.
The code I used is
<input name="delRul_2" id="delRul_2" value="Delete" onclick="deleteRule(3);" type="button">
I like to decrement the parameter 3 as 2 while deleting a row.
ASKER CERTIFIED SOLUTION
Avatar of David S.
David S.
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
I am working on this solution. I will surely get back to you
thanks again Kravimir
Thanks Kravimir ....the solution you gave pointed me to the right direction but it was not enough to reach the destination..:)