I'm rendering a form with radio buttons using JQuery and then trying to read the value of the selected radio option when the submit button is clicked. However all i get is undefined values.
I tried to return .val() and read an attribute of the input element like .attr("name"), but everything returns 'undefined'.
Here is how i create the input elements inside a form:
let options = $("<div></div>");
for (let answer of questionnaire[currentQuestion].answers) {
let a = $("<input></input>").attr({
"name":questionnaire[currentQuestion].name,
"type":"radio",
"value":answer.value
});
let l = $("<label></label>").text(answer.label);
options.append(a,l);
}
When inspecting the HTML elements in browser page, each input element looks like this:
<input name="comfortfood" type="radio" value="steak">
<label>Medim-rare flat iron Steak</label>
And this is how i try to read the value:
$('input:radio[name='+questionnaire[currentQuestion].name+']:checked').val()
I checked other threads here (like this one) but still can't get my code to work. I'm new to all this so probably missing something obvious.
EDIT: I ended up creating a click event on each radio button and then reading value with event.currentTarget
as suggested by @Sakata Gintoki in his comment below