Keshvi Srivastava
Keshvi Srivastava

Reputation: 89

How to access dynamically created button?

btnUpdate = document.createElement("BUTTON");
var t = document.createTextNode("Update");
btnUpdate.id = 'update0';
btnUpdate.appendChild(t);
tabCell.appendChild(btnUpdate);

I have a simple line of code where I have created a button with my javascript. How do I access this button through the same javascript file? I want to add onClick feature to it.

document.getElementById("update0").onclick = edit_row(0);

I tried doing so by adding the above line of code, but now it won't display the table but straight away jumps to the edit_row() function.

Edit:

function showCustomer() {

  var obj, dbParam, xmlhttp, myObj, x, txt = "",tabCell;    
  var btnUpdate;
  obj = { "table":"Successful", "limit":20 };
  dbParam = JSON.stringify(obj); 
  xmlhttp = new XMLHttpRequest();
  xmlhttp.onreadystatechange = function() {
  if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
    myObj = JSON.parse(xmlhttp.responseText);
    console.log(myObj);
    var col = [];
    for (var i = 0; i < myObj.length; i++) {
        for (var key in myObj[i]) {
            if (col.indexOf(key) === -1) {
                col.push(key);
            }
        }
    }
    key="Update";
    col.push(key);
    console.log(col);
    // CREATE DYNAMIC TABLE.
    var table = document.createElement("table");

    // CREATE HTML TABLE HEADER ROW USING THE EXTRACTED HEADERS ABOVE.

    var tr = table.insertRow(-1);                   // TABLE ROW.

    for (var i = 0; i < col.length; i++) {
        var th = document.createElement("th");      // TABLE HEADER.
        th.innerHTML = col[i];
        tr.appendChild(th);
    }

    // ADD JSON DATA TO THE TABLE AS ROWS.
    for (var i = 0; i < myObj.length; i++) {

        tr = table.insertRow(-1);
        tabCell = null;
        for (var j = 0; j < col.length-1; j++) {
            tabCell = tr.insertCell(-1);
            tabCell.innerHTML = myObj[i][col[j]];
        }
        tabCell = tr.insertCell(-1);
        btnUpdate = document.createElement("BUTTON");
        var t = document.createTextNode("Update");
        btnUpdate.id = 'update'+i;
        btnUpdate.appendChild(t);
        tabCell.appendChild(btnUpdate);
    }
    tr = table.insertRow(-1);

        tabCell = null;
        for (var j = 0; j < col.length-1; j++) {
            tabCell = tr.insertCell(-1);
            tabCell.innerHTML = " ";
        }
        tabCell = tr.insertCell(-1);
        var btn = document.createElement("BUTTON");
        var t = document.createTextNode("Add Row");
        btn.appendChild(t);
        tabCell.appendChild(btn);

        document.getElementById("update0").addEventListener = function (){
            edit_row(0);
        };

    // FINALLY ADD THE NEWLY CREATED TABLE WITH JSON DATA TO A CONTAINER.
    var divContainer = document.getElementById("showData");
    divContainer.innerHTML = "";
    divContainer.appendChild(table);
    }
  };
  xmlhttp.open("POST", "http://localhost:8090/Vaccine", true);
  xmlhttp.setRequestHeader("Content-type", "application/JSON");
  xmlhttp.send("x=" + dbParam);  
}

function edit_row(no)
{
    alert("HELLO");
}

Upvotes: 1

Views: 1299

Answers (6)

Guillaume Georges
Guillaume Georges

Reputation: 4020

With this line :

document.getElementById("update0").onclick = edit_row(0);

You are not "attaching" the click event to the edit_row function. You're setting the onclick property with the result of the edit_row(0) invokation.

Also, don't use the onclick property.

Use the addEventListener function instead.

document.getElementById("update0").addEventListener("click", function () {
    edit_row(0);
});

If you need a reason : by overwriting the onclick property, you could be disabling any other click event listener on your elements. By using addEventListener(), you can have several events listener on the same element/event couple.

And you can do this right after you created the button. You don't need to get it by its id later.

Your code would look like this :

btnUpdate = document.createElement("BUTTON");
var t = document.createTextNode("Update");
btnUpdate.id = 'update0';
btnUpdate.appendChild(t);
btnUpdate.addEventListener("click", function () {
    edit_row(0);
});

Upvotes: 1

mplungjan
mplungjan

Reputation: 177691

You call the function when you have () at the end so

document.getElementById("update0").onclick = edit_row(0); 

will immediately call edit_row

Why not do this instead:

btnUpdate = document.createElement("BUTTON");
var t = document.createTextNode("Update");
btnUpdate.id = 'update0';
btnUpdate.onclick=function() {
   edit_row(this.id.replace("update","")); // or use a data-attribute
}
btnUpdate.appendChild(t);
tabCell.appendChild(btnUpdate);

or use event delegation:

Native JS equivalent to jquery delegation

Upvotes: 0

Henrique Limas
Henrique Limas

Reputation: 307

It seems that your button is not in the DOM yet, so you are not able to find it with document. You can use the variable btnUpdate if it is in the same file like btnUpdate.onclick = function() {}, or using addEventListenerlike btnUpdate.addEventListener('click', function() {}).

Also, it seems you are executing the edit_row(0) function. You need to put it inside a function like

btnUpdate.addEventListener('click', function() {
  edit_row(0);
})

Upvotes: 0

Vlad Trostinsky
Vlad Trostinsky

Reputation: 26

Try this:

btnUpdate = document.createElement("BUTTON");
var t = document.createTextNode("Update");
btnUpdate.id = 'update0';
btnUpdate.appendChild(t);
tabCell.appendChild(btnUpdate);
btnUpdate.addEventListener("click", (e) => {
   // this linked to btnUpdate
   // Here make whatever you want
   // You can call edit_row now
   edit_row(0)
})

Upvotes: 0

Quentin
Quentin

Reputation: 943207

How do I access this button through the same javascript file?

The same way you've been accessing it all along.

It is stored in the btnUpdate variable. Use that.


but now it won't display the table but straight away jumps to the edit_row() function.

That is because you are calling edit_row and setting its return value as the click handler.

Since you want to pass arguments to it, the easiest thing to do is to create a new function.

function edit_row_first_argument_0 () {
    edit_row(0);
}

button.addEventListener("click", edit_row_first_argument_0);

(You can use an anonymous function expression, I use the verbose approach above for clarity).

Upvotes: 0

Suresh Atta
Suresh Atta

Reputation: 121998

You have to do that in callback of on click event. If you inline, it executes directly when javascript reading your code.

document.getElementById("update0").onclick = function (){
    edit_row(0);
};

Upvotes: 1

Related Questions