Chewynugget Chewynugget - 7 months ago 15
Javascript Question

Function of appended child button

I'm trying to make code to ask for your name, which then says, "Hello, _____, my name is Dolly." Then three buttons appear with options of what to do to Dolly.

Is there any way I can add a function onclick of the spawned buttons to create a response accordingly? I apologize if it's a bit messy and not dry, I'm kinda new to this.

<body>
<p id="dolly"></p>
<div id="div1">
<h3 id="try" class="enterN">Please enter your name</h3>
<input type="text" id="name" value="" placeholder="Please enter your name">
<button id="submit" onclick="yourName()">Enter</button>
</div>

<script>
function yourName() {
var x = document.getElementById("name").value;
if (x.length != 0) {
document.getElementById("dolly").innerHTML = "Hello, " + x + ", My name is Dolly.";
var btn = document.createElement("BUTTON");
var t1 = document.createTextNode("Say Hello");
btn.appendChild(t1);
document.body.appendChild(btn);
var btn = document.createElement("BUTTON");
var t2 = document.createTextNode("Hug Dolly");
btn.appendChild(t2);
document.body.appendChild(btn);
var btn = document.createElement("BUTTON");
var t3 = document.createTextNode("Kill Dolly");
btn.appendChild(t3);
document.body.appendChild(btn);

$(document).ready(function(){
$("#div1").remove();
});

} else {
document.getElementById("dolly").innerHTML = "Please enter your name.";
}
}
</script>
</body>

Answer

Hi you can set attribute onclick and pass your function like this

var btn = document.createElement("BUTTON");
var t1 = document.createTextNode("Say Hello");
btn.setAttribute("onclick", "function1()");
btn.appendChild(t1);
document.body.appendChild(btn);
Comments