Reputation: 233
I am getting Json data in output and appended to table with edit option, so what I want is when click on Edit of td then clicked td element text should change from 'Edit' to 'Save' and when click on 'save' again it change to edit, but at time one td element should change from 'Edit' to 'Save' at atime only one 'Save' should active and others remain 'Edit' .
<table class="append_data">
<tr>
<th>Company</th>
<th>Contact</th>
<th>Country</th>
<th>Action</th>
</tr>
</table>
//script to get data:
$.ajax({
url: "<?= base_url('controller/get_users') ?>",
type: 'POST',
data: {
},
success: function (myJSON) {
var output = myJSON;
var html = '';
$.each(output, function (key, value) {
html += '<tr>';
html += '<td>' + value.name + '</td>';
html += '<td>' + value.mobile + '</td>';
html += '<td>' + value.id + '</td>';
html += '<td><a href="javascript:void(0);" style="text-decoration:none;" class="edit_user" data-id="' + value.id + '"><span class="change_res' + value.id + '">Edit</span></a></td>';
html += '</tr>';
});
$('.append_data tbody').append(html);
},
error: function (xhr) {
alert(xhr.status);
}
});
//script to change text
$("body").on('click', '.edit_user', function () {
var userid = $(this).attr("data-id");
$(this).text('Save').siblings().text('Edit');
});
getting output:
Expected output:
Upvotes: 2
Views: 1738
Reputation: 24001
you can try
$("body").on('click', '.edit_user', function () {
var userid = $(this).attr("data-id");
$('.edit_user').not(this).text('Edit'); // back all the edit_user to Edit but not this
$(this).text(($(this).text().trim() == 'Save') ? 'Edit' : 'Save'); // change the text for this between Edit or Save
});
Explanation :
$('.edit_user').not(this).text('Edit');
back all other elements text to Edit
$(this).text().trim() == 'Save') ? 'Edit' : 'Save'
is a short hand method of if statement .. means if the text of the element is Save
set it to Edit and vice versa .. and about .trim()
here for double check that the text is exactly equal the string
Upvotes: 2