9

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?

1
  • 6
    That's probably the worst way to add an element imaginable ? Commented Apr 9, 2014 at 16:43

2 Answers 2

26

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);
Sign up to request clarification or add additional context in comments.

10 Comments

Darn, you beat me to it.
Just a compatibility observation: In Internet Explorer, addEventListener() is only supported from version 9 and higher. I would suggest button.onclick = function(){...}.
@Kekas onclick only supports one event, whilst this allows multiple events. For older versions I believe attachEvent is what you would use.
Right, but if you only need one event, onclick should do the trick.
@Kekas - If old IE is an issue, you'd use attachEvent, and there are a million examples online on how to do that, so I wont write it all in the answer, but I believe that addEventListener should be used over onclick whenever possible, which is always.
|
0

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.

1 Comment

Good for you, post your own answer when you're able to fix the issue, but this is still the most horid way to add an element ever invented, and you should consider rewriting it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.