Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

can't get value of dynamic remove/edit HTML table using javascript

I'm trying to write a piece of code that can handle remove or editing of dynamic HTML table. I've googled and stackoverflow this problem, I see many samples but none of them worked properly.

Here is my code:

server.js

router.get('/bookShow', (req, res) => {
    bookModel.find({isDeleted : false}).sort('-pageCount').exec((err, data) => {
        if (data) {
            res.send(data);
        }
    });
});

BookModel in Database:

enter image description here

bookShow.html

<script>
    $(document).ready(() => {
        $.getJSON('/bookShow', (json) => {
            var tr;
            for (var i = 0; i < json.length; i++) {
                tr = $('<tr/>');
                tr.append("<td>" + "<button class='deleteButton'>" + "<i class='material-icons'>delete</i></button>" + "</td>");
                tr.append("<td>" + "<button class='editButton'>" + "<i class='material-icons'>edit</i></button>" + "</td>");
                tr.append("<td>" + json[i].pageCount + "</td>");
                tr.append("<td>" + json[i].name + "</td>")
                $('table').append(tr);
            }
        });

        $(document).on('click', '.deleteButton', () => {
            console.log($(this));
        })
    });  
</script>

Problem: As it seen in bookShow.html, I've declared an eventlistener whenever .deleteButton clicked. But I can't access the other fields of that table row. for example when I click on delete button of Behzad, I can't be notified the book name and its page count.

enter image description here

like image 920
Mostafa Ghadimi Avatar asked Aug 06 '26 15:08

Mostafa Ghadimi


1 Answers

By using ES6's Arrow function () => {} the this is not any more what you're used to like by using function. It's window, because of their nature of lexical scope binding. Not any more the jQuery's representation of the DOM Element "this".

$(this) =
jQuery.fn.init [Window] by usign Arrow function () => {}
jQuery.fn.init [button.deleteButton] by using Function function () {}

so your solution would be to use the standard $(document).on('click', '.deleteButton', function() {

or to add the click on button creation - which is doable by making your button an live in-memory jQuery element $('<button>', {on:{click(){}}, appendTo:'selector'}) instead of HTML string literal.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

Here's a remake:

const json = [ // You use getJSON, I'll use this for my demo
{"name": "King of the Jungle","pageCount": 543},
{"name": "The Things I've Done","pageCount": 198}
];

jQuery($ => {

  // $.getJSON

  $('table').append(json.map((book, i) => 
    $('<tr>', {
      html: `
        <td>${i+1}</td>
        <td>${book.name}</td>
        <td>${book.pageCount}</td>
      `,
      append: [       // or use prepend
        $('<td>', {
          append: $('<button>', {
            class: "buttonEdit",
            html: "<i class='material-icons'>edit</i>",
            on: {
              click() { // Same as using `click: function () {`
                console.log(`Editing ${book.name} by:`, this); // this = <button>
              }
            }
          })
        }),
        $('<td>', {
          append: $('<button>', {
            class: "buttonDelete",
            html: "<i class='material-icons'>delete</i>",
            on: {
              click() {
                console.log(`Deleting ${book.name} by:`, this);
              }
            }
          })
        }),        
      ]
    })
  ));

  // END $.getJSON

});
table {
  width: 100%;
}

td {
  border: 1px solid #ddd;
}
<table></table>
<script src="//code.jquery.com/jquery-3.1.0.js"></script>
like image 90
Roko C. Buljan Avatar answered Aug 10 '26 22:08

Roko C. Buljan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!