Ahmed ilyas
Ahmed ilyas

Reputation: 5822

Dynamically remove row and update indices

I have a page where a user can add a row of information:

   <div id="refItem">
    FirstName 
    LastName
   </div>

users can keep pressing the add button and it will then keep appending to that div another row of data by manipulating the DOM. It also updates the ViewModel collection indices too. The ViewModel contains a collection of which has, FirstName and LastName as above

When the View loads, it uses the Model to render the data as above (so imagine a for loop rendering the row of data)

Question:

How can I delete the row from client side and update the indices at the same time before the user hits the submit button? what JQuery do I need to get hold of the row to delete and then update the DOM?

Upvotes: 0

Views: 2022

Answers (1)

McGarnagle
McGarnagle

Reputation: 102743

It depends on your exact markup, but in general:

  • use $(selector).remove() to delete the row
  • loop through the items and use $(this).prop("name", "value") to update the index.

Here's an example (Fiddle)

function del(index) {
    var toDelete = $("#refItem"+index);
    toDelete.remove();

    var id=1;
    // select all elements with id starting with "refItem", and loop
    $("div[id^=refItem]").each(function(item) {
        // update the "id" properties
        $(this).prop("id", "refItem"+id++);
    });
}

As an alternative, you could also put a button in each row, and remove it using a relative selector like (this).parent().remove(). (Fiddle).

Upvotes: 4

Related Questions