skip to Main Content

I’ve recently been trying to learn to use Jquery. I am trying to change cells in a table using Bootstrap modal and JQuery. I have succeeded in getting data from table to modal. The problem I encountered was when I wanted to update data from modal to the table. here is my script:

    $(document).on("click", "#edit-btn", function () {
        $('#editProductModal').modal('show');
        $tr =$(this).closest('tr');
        var data= $tr.children("td").map(function(){
            return $(this).text();
        }).get();
        $('#edit_no').val(data[0]);
        $('#edit_orderuid').val(data[1]);
        $('#edit_productname').val(data[2]);
        $('#edit_qty').val(data[3]);
        $('#edit_weight').val(data[5]);
        $('#edit_price').val(data[6]);
        $('#edit_discount').val(data[7]);
    });

//Update
$(document).on("click", "#update-product", function () {
    var data= $tr.children("td").map(function(){
        return $(this).text();
    }).get();
    $(data[3]).text($('edit_qty').val())
    $('#editProductModal').modal('hide');

});

when I tried it the cell did not change. can you tell me where the problem is?

2

Answers


  1. Please don’t learn jQuery in 2024. Just do it with real javascript, you’ll be much happier and better prepared for future work if you avoid that path altogether.

    To answer your question though, in your update function add a breakpoint or log the value of data to the console and you’ll see that it’s an array of strings instead of an array of DOM element references. It should just be var data = $tr.children("td"), then when using data[3] you’ll be able to set the value of that node

    Login or Signup to reply.
  2. While the other answer is correct, you could create a mapping array and simplify your work, like

        let modalMap = ['edit_no', 'edit_orderuid', 'edit_productname', 'edit_qty', 'edit_weight', 'edit_price', 'edit_discount'];
    

    and then use it like

        $(document).on("click", "#edit-btn", function () {
            $('#editProductModal').modal('show');
            $tr =$(this).closest('tr');
            var data = $(this).closest('tr').children("td");
            for (let index = 0; index < modalMap.length; index++) {
                $("#" + modalMap[index]).val(data[index]);
            }
        });
    

    and

    //Update
    $(document).on("click", "#update-product", function () {
        var data= $(this).closest('tr').children("td");
        $(data[data.indexOf("edit_qty")]).text($('#edit_qty').val());
        $('#editProductModal').modal('hide');
    
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search