NTM NTM - 1 year ago 79
Javascript Question

Adding onclick event on dynamic checkbox

I'm trying to make a 'CRUD' in pure Javascript, it's almost done, the only thing that I need is preparing the inputs with the value of

  • , to do it, I'd like to add an onclick event in checkbox that is created dynamically in the function insert(), but everytime that a click in the checkbox nothing happens.

    <!DOCTYPE html>
    window.onload = function(){
    btnInsert = document.getElementById("btnInsert");
    btnEdit = document.getElementById("btnEdit");
    btnDelete = document.getElementById("btnDelete");
    vname = document.getElementById("tbName");
    ul = document.getElementsByTagName("ul")[0];

    btnInsert.onclick = insert;
    btnDelete.onclick = remove;

    function insert(){
    li = document.createElement("li");
    li.innerHTML = vname.value;
    li.innerHTML += " <input type='checkbox' onclick='select()' value='Select' /> Update";
    vname.value = "";

    function select(){

    function remove(){
    var lis = document.getElementsByTagName("li");
    for(i = 0; i<lis.length; i++){
    lis[i].onclick = function(){
    <label for="tbName">Name: </label>
    <input name="tbName" id="tbName"/><br /><br />
    <button id="btnInsert">Insert</button>
    <button id="btnEdit">Edit</button>
    <button id="btnDelete">Delete</button>
    <br /><br />

  • Answer Source

    It seems the name select is causing conflict since I could get your code working with the following changes:


    li.innerHTML += " <input type='checkbox' onclick='sel()' value='Select' />Update";


    function sel(){

    Further tests show that if we log the contents of the function with:

    li.innerHTML += " <input type='checkbox' onclick='console.log(select.toString)' value='Select' />Update";

    the console shows the following

    function select() { [native code] }

    So my guess is that select is the name of a function already defined by the API, possibly related to HTMLInputElement.select(), hence why you can't use it as a name for your functions.

    In short, your code triggers another select function, not the one you defined in your source code.

    Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download