function boxes() {
let body = document.querySelector("body");
let todoLabel = document.createElement("label");
//
let priorityHigh = document.createElement("input");
priorityHigh.type = "radio";
priorityHigh.value = "High";
priorityHigh.name = "radio";
//
let priorityMedium = document.createElement("input");
priorityMedium.type = "radio";
priorityMedium.value = "Medium";
priorityMedium.name = "radio";
//
let priorityLow = document.createElement("input");
priorityLow.type = "radio";
priorityLow.value = "Low";
priorityLow.name = "radio";
todoLabel.appendChild(priorityHigh);
todoLabel(priorityMedium);
todoLabel.appendChild(priorityLow);
body.appendChild(todoLabel);
}
function getValue() {
let priorityInput = document.getElementsByName("input[type='radio'][name=radio]").value;
let button = document.createElement("button");
document.body.appendChild(button);
button.addEventListener("click", () => {
console.log(priorityInput);
});
}
So im expecting to get the the value of whatever radio button is clicked, say I clicked the first one, I would expect to get the value of "High" or if I decide to click the second one then I expect to get the value of "Medium" but I get back null
2
Answers
Try out:
This should select the first checked radio button with the name "radio" and save the value in the "priorityInput" variable.
I use the suggestion from @Dusto to find a solution for you:
The source of your trouble is placed into the function getValue(). You have to just replace and move line *1 :
Additional, for a good behaviour you schould check the value
priorityInput
to null in case no selection has being made.Also there is a small error in boxes(): The line
todoLabel(priorityMedium);
still needs.appendChild
.