简体   繁体   中英

Change text of td element when click on it using jquery

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:

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' $(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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM