Admin Letsgo
Admin Letsgo

Reputation: 99

Run function when a user clicks a button?

I am trying to call a function using the appended button in the appended table.

Here is my code snippet.

function userAction(){
    window.alert("Hi");
   }

var newbtn=document.createElement('button');

   newbtn.setAttribute('type','button');
   newbtn.setAttribute('onclick',userAction);
   newbtn.setAttribute('class','btn btn-primary mt-4');
   newbtn.innerHTML='Review'
   tr.appendChild(newbtn);

Click below link for the full code

https://drive.google.com/file/d/1t6M5L_6tXYdGnemI8t0qlcFb93jkbx0I/view?usp=sharing

I expect it to create a pop up alert when the user clicks the button, but it doesn't seem to be working. This is what the element looks like when I inspect it:

<button type="button" onclick="function userAction(){
    window.alert(&quot;Hi&quot;);
     }" class="btn btn-primary mt-4">Review</button>

What might I be doing incorrectly? Thanks!

Upvotes: 1

Views: 270

Answers (2)

gaetanoM
gaetanoM

Reputation: 42054

onclick is a property and not an attribute. Hence you cannot use setAttribute.

Change it from:

newbtn.setAttribute('onclick',userAction);

to:

newbtn.onclick = userAction;

function userAction(){
    window.alert("Hi");
}

 var tr = document.querySelector('tr');
var newbtn=document.createElement('button');

newbtn.setAttribute('type','button');
newbtn.onclick = userAction;
newbtn.setAttribute('class','btn btn-primary mt-4');
newbtn.innerHTML='Review'
tr.appendChild(newbtn);
<table>
    <tbody>
    <tr><td>simple cell</td></tr>
    </tbody>
</table>

Upvotes: 2

Kody R.
Kody R.

Reputation: 2460

Add a Click Event Listener like so instead of setAttribute:

newbtn.addEventListener('click', () => userAction());

Upvotes: 2

Related Questions