Javascript - Add Button With Onclick Attribute Dynamically
I am using this code, which adds button: document.getElementById('items').innerHTML=document.getElementById('items').innerHTML+ ('
Solution 1:
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);
Solution 2:
I managed to do it!
document.getElementById("items").innerHTML=document.getElementById("items").innerHTML
+('<input type="button" onClick="alert(\''+document.getElementById("add").value+'\')"
value="'+document.getElementById("add").value+'"><br>')
I replaced "
(double quote) with \'
(single quote) in alert.
Works, button added, alert displayed.
Post a Comment for "Javascript - Add Button With Onclick Attribute Dynamically"