1
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");
}
  • 1
    After you've created the button, you can add a listener to it, like so: `btnUpdate.addEventListener('click', function () {edit_row(0);});` The added listener will follow the button, no matter where ever you're going to append/insert the button later. – Teemu Feb 14 '18 at 10:50

6 Answers6

1

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);
};
Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
  • Uncaught TypeError: Cannot set property 'onclick' of null at XMLHttpRequest.xmlhttp.onreadystatechange It is giving me this error for that line. – Keshvi Srivastava Feb 14 '18 at 10:49
  • @KeshviSrivastava Could you please post full codes ? Looks like your element is null. Probably by accessing in a wrong way or your element does not exist. – Suresh Atta Feb 14 '18 at 10:49
1

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);
});
Guillaume Georges
  • 3,878
  • 3
  • 14
  • 32
0

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).

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • As you can see above (I've uploaded the whole code now) I have multiple buttons all with the same var name. How do i access one specific button then? – Keshvi Srivastava Feb 14 '18 at 10:56
  • @KeshviSrivastava — You know how you use `btnUpdate.id = 'update0';` to set the `id` property of the specific button you want to set? And you get the right button by doing it before you overwrite the `btnUpdate` variable with a new value? The same way. – Quentin Feb 14 '18 at 10:58
  • i'm sorry but I still dont get it. Could you edit the code and share here? – Keshvi Srivastava Feb 14 '18 at 11:00
0

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)
})
0

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);
})
Henrique Limas
  • 307
  • 1
  • 10
0

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

mplungjan
  • 169,008
  • 28
  • 173
  • 236