John Davidson

javascript - Edit table row with jquery and twig

0 comments
Message:


I have table in my twig template generated dynamically:


{% for a in abc %}
<tr>
<td>
{{ a.key }}
</td>
<td>
{{ a.value }}
</td>
<td class="td-actions">
<button id='EditSave' data-text="Save" data-id="{{ a.id }}">Edit</button>
<button id='Cancel' data-text="Cancel" style="display:none;">Cancel</button>
</td>
</tr>
{% endfor %}

I made my js function that will change attribute on click.


I am new in js and what I want to accomplish further is that on specific row 'Edit' click these two field become editable.


I know how to implement ajax but don't know how to access is with twig and jquery.


My func:


$(document).ready(function(){

//getting id of specific column
var id = $(this).data('id');

$("#EditSave").click(function(){
var btnText = $(this).text();
if(btnText === 'Edit')
{
$(this).text('Save');
$('#Cancel').show();
}
else
{
$(this).text('Edit');
$('#Cancel').hide();
}
});

$('#Cancel').click(function(){
$(this).hide();
$('#EditSave').text('Edit');
});
});


My Answer:






{% for item in abc %}





{% endfor %}
Name Age Action
{{ item.name }} {{ item.age }}

{% endfor %}
To edit a table row using jQuery, you can add a click event listener to the "Edit" button and then update the row with input fields for editing. Here's an example of how you can achieve this:
javascript
$(document).ready(function() {
$('.edit-btn').click(function() {
var row = $(this).closest('tr');
var name = row.find('td:eq(0)').text();
var age = row.find('td:eq(1)').text();
row.html('');
});
$(document).on('click', '.save-btn', function() {
var row = $(this).closest('tr');
var name = row.find('input:eq(0)').val();
var age = row.find('input:eq(1)').val();
row.html('' + name + '' + age + '');
});
});

In this code snippet, when the "Edit" button is clicked, the table row is replaced with input fields containing the current values. When the "Save" button is clicked, the input values are retrieved and used to update the table row.

Rate this post

4 of 5 based on 4907 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us