Search code examples
javascriptlistener

javascript button event dosent work correctly


I have a simple html table and want to dynamically add rows to it. Some cells of the table are buttons for which I have set onclick events. inside the listener function I just log hello. the problem is that, when I push the button, it prints 123 on the console then the page and console are automatically refreshed.

here's my code:

let row= document.getElementById("table-body"); 
let cell = row.insertCell(0);
let serial = 123;
cell.innerHTML = "<button" + " onclick='removeServiceMap( " + serial + " )' " + ">" + "حذف" + "</button>";

and removeServiceMap function is as follow:

function removeServiceMap (serial) {
     console.log(serial);
}

does anybody know what's wrong with this code?


Solution

  • You want to make the elements using:

    const elm = document.createElement("tag");
    

    then you can add an event listener to it using:

    elm.addEventListener("click", (e) => {
        console.log(e.target.textContent);
    });
    

    If you want to delete the row, you can just select the parent and remove it.

    elm.addEventListener("click", (e) => {
        console.log(e.target.parentElement.remove());
    });
    

    To add the element you made to the DOM, select an element and use appendChild();

    document.querySelector(selector).appendChild(element);