Below are my HTML and javascript codes:
HTML
<body>
<div>
<form id="radioform">
<fieldset>
<div class="mainbox">
<label for="gender"><strong>Gender</strong></label><br>
</div>
<div id="optionbox">
<input type="radio" id="female" name="gender" value="female" /> Female
<input type="radio" id="male" name="gender" value="male" /> Male
</div>
<input type="submit" value="Submit" class="submit-btn" />
</fieldset>
</form>
</div>
</body>
<script src="script.js"></script>
Javascript
var genderval = "null";
const form = document.getElementById("radioform");
form.addEventListener("submit", (e) => {
e.preventDeafult();
genderval = document.querySelector(
'input[name="gender"]:checked').value;
});
console.log(genderval); //test
if(genderval === "female") {
console.log("Female");
} else if(genderval === "male") {
console.log("Male");
}
It only prints out "null" no matter which radio button I select.
It seems like checked is not working properly in the querySelector but I do not understand why.
(var genderval = "null"; is just for the testing. It returns me an uncaught reference error when I delete the line.)
2
Answers
Use
let genderval;
to define your variable. It’se.preventDefault();
. Also, put yourif...else
statement inside theaddEventListener()
method.The variable is
undefined
at first, but once you check any of both radio buttons and click on "submit", it’ll print the corresponding value.e.preventDeafult();
as correct method ise.preventDefault();
.