Trung Vu
Trung Vu

Reputation: 541

update data attribute value

I'm trying to update a data-id on Edit button, but for some reason it's stay on one id, which has taken it from first pick. Here is my code:

<input type="text" class="form-control" id="clr_name" name="clr_name">

<button type="submit" class="btn col-xs-6 hide edit">Edit</button>
<button type="submit" class="btn col-xs-6 hide delete">Delete</button>

<div class="col-xs-6">
  <table class="table table-striped">
    <tbody>

      <tr>
        <td>Black</td>
        <td data-id="1" class="edit">edit</td>
      </tr>

      <tr>
        <td>White</td>
        <td data-id="2" class="edit">edit</td>
      </tr>

      <tr>
        <td>Blue</td>
        <td data-id="3" class="edit">edit</td>
      </tr>

    </tbody>
  </table>
</div>
<p>ID: <span class="dataId"></span></p>

JavaScript

$("tbody").on("click", "td.edit", function() {
  formAction($(this).attr("data-id"), $(this).parent(), $(this).prev('td'));
});

function formAction(id, parent, prev) {
  $(".dataId").text(id);
  $("tr").attr('data-edit', null);
  parent.attr("data-edit", true);
  $("#clr_name").val(prev.text());
  $(".edit, .delete").attr("data-id", id);
}

jsfiddle.net/52hyktb4/

Upvotes: 1

Views: 1785

Answers (1)

Dekel
Dekel

Reputation: 62676

The reason it stays on one id is that you have this line in your function:

$(name + " .edit, " + name + " .delete").attr("data-id", id);

After your first click - you set the current it to all of the .edit and .delete elements in your document.

You can just remove this line and your code should work as you expected.

Upvotes: 2

Related Questions