I am creating a radio button using makeRadioButton function, here I am passing the name and value, I also tried passing the name of a function the same way, and it doesn't seem to work. Please help me how to pass a function to a newly created radio button.
function makeRadioButton(name, value, text) {
var label = document.createElement("label");
var radio = document.createElement("input");
radio.type = "radio";
radio.name = name;
radio.value = value;
**radio.onclick = "createDropdown()";**
label.appendChild(radio);
label.appendChild(document.createTextNode(text));
return label;
}
Your code works fine you just have to append your returned value to the document.
Try this example below
function makeRadioButton(name, value, text) { var label = document.createElement("label"); var radio = document.createElement("input"); radio.type = "radio"; radio.name = name; radio.value = value; radio.onclick = createDropdown; label.appendChild(radio); label.appendChild(document.createTextNode(text)); return label; } let lable = makeRadioButton("myRadio", null, "How old are you"); document.body.append(lable); function createDropdown(){ console.log("CLICKED"); }
Try setting onclick
to directly be the function createDropdown
:
function makeRadioButton(name, value, text) { var label = document.createElement("label"); var radio = document.createElement("input"); radio.type = "radio"; radio.name = name; radio.value = value; radio.onclick = createDropdown; label.appendChild(radio); label.appendChild(document.createTextNode(text)); return label; } function createDropdown(event) { console.log("createDropdown"); }; document.body.appendChild(makeRadioButton("radio", null, "radio"));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.