Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript - Add button with onClick attribute dynamically

I am using this code, which adds button:

document.getElementById("items").innerHTML=document.getElementById("items").innerHTML+
('<input type="button" value="'+document.getElementById("add").value+'"><br>');

It works. Now i am adding onClick attribute:

document.getElementById("items").innerHTML=document.getElementById("items").innerHTML+
    ('<input type="button" onClick="alert("'+document.getElementById("add").value+'")"
     value="'+document.getElementById("add").value+'"><br>');

I want to display an alert with button name (add is button id) if I click on button. But no alert displayed. Probably I made i mistake in onClick, because button is being added.
Whats wrong with my code?

like image 872
nicael Avatar asked Apr 09 '14 16:04

nicael


People also ask

How can we call onclick function on dynamically created button in jquery?

onclick = function () { alert("hi jaavscript"); };


1 Answers

Do it the proper way

var items  = document.getElementById("items"),
    button = document.createElement('input'),
    br     = document.createElement('br'),
    add    = document.getElementById("add").value;

button.type  = 'button';
button.value = add;
button.addEventListener('click', function() {
    alert(add);
}, false);

items.appendChild(button);
items.appendChild(br);
like image 131
adeneo Avatar answered Sep 23 '22 18:09

adeneo