manikandan manikandan - 3 months ago 14
Javascript Question

Java script function gets called when i pass arguments

I have created a dynamic button when that button gets clicked it will invoke a javascript function with an arguments but the other lines are getting skipped during this process

function mainradio() {
var dyndiv = document.createElement("div");
dyndiv.id = "div_temp";


var dynradiogroup = document.createElement("label");
dynradiogroup.name="rdlbl";
dynradiogroup.className="rdmainclass";
dynradiogroup.innerHTML="Please enter your question";

var nextradio = document.createElement("input");
nextradio.type="button";
nextradio.id="nxtbtnid";
nextradio.name="nxtbtnnme";
nextradio.value="Add more button";
nextradio.onclick =createRadio(dyndiv.id);

dyndiv.appendChild(dynradiogroup);
dyndiv.appendChild(nextradio);
document.getElementById("dynElements").appendChild(dyndiv);
}


the dynamically created label and button are not attached to the div that was also created dynamically
dyndiv.appendChild(dynradiogroup);
dyndiv.appendChild(nextradio);
document.getElementById("dynElements").appendChild(dyndiv);
function get invoked before these 3 statements gets executed.

Answer

Use nextradio.onclick = createRadio.bind(this, dyndiv.id); or nextradio.onclick = () => { createRadio(dyndiv.id); };