Targetting A From It's Parents With Data-attributes Using Jquery
I'm developing an editable table feature as described in a previous post: Editable row in a table - is using the record ID on a element bad practice? I've got the followSolution 1:
You can use find()
along with :first
(or :eq(0)
) to get the first td
within the row. You can also change the text and class of the clicked button using text()
and addClass()
respectively. Finally you can place the content in an input
by appending it to the td
. Try this:
$('.editBtn').click(function() {
var $button = $(this).addClass('save').text('Save');
var $tr = $button.closest('tr');
var id = $tr.data('id');
var $td = $tr.find('td:first');
$td.html('<input value="' + $td.text() + '" />');
});
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><table><trdata-id="2"><td>Foo</td><td><buttonclass="editBtn">Edit</button></td></tr><trdata-id="3"><td>Bar</td><td><buttonclass="editBtn">Edit</button></td></tr></table>
I'm developing an editable table feature as described in a previous post: Editable row in a table - is using the record ID on a element bad practice? I've got the follow
Solution 1:
You can use find()
along with :first
(or :eq(0)
) to get the first td
within the row. You can also change the text and class of the clicked button using text()
and addClass()
respectively. Finally you can place the content in an input
by appending it to the td
. Try this:
$('.editBtn').click(function() {
var $button = $(this).addClass('save').text('Save');
var $tr = $button.closest('tr');
var id = $tr.data('id');
var $td = $tr.find('td:first');
$td.html('<input value="' + $td.text() + '" />');
});
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><table><trdata-id="2"><td>Foo</td><td><buttonclass="editBtn">Edit</button></td></tr><trdata-id="3"><td>Bar</td><td><buttonclass="editBtn">Edit</button></td></tr></table>
Post a Comment for "Targetting A From It's Parents With Data-attributes Using Jquery"