Hi can you help me with if else? I tried to create an alert box whenever the radio is selected. however it doesn’t work well. can you tell me please whats wrong?
Thank you!
<html>
<head>
<title> Example of the radio checked property</title>
</head>
<body>
<script language="JavaScript">
function checkButton(){
if(document.form1.button1.checked == true){
alert("Box1 is checked");
} else if(document.form1.button2.checked == true){
alert("Box 2 is checked");
}
}
</script>
<form name="form1">
<input type="radio" name="button1" value ="check1">Box 1
<br>
<input type="radio" name="button1" value ="check2">Box 2
<br>
<input type="button" value="Get Checked" onClick='checkButton()'>
</form>
</body>
</html>
The form element with the name="button2" does not exist (you have button1 twice), so the script breaks when doing the 2nd check (you can see the error in the console). As you probably need both radios to have the same name, you might iterate over them using the .forEach() method like so:
document.form1.button1.forEach(function (current, index) {
if (current.checked) {
console.log('Box ' + (index + 1) + ' is checked')
}
})
Or since only one radio can be checked anyway, you might convert the radio list to an array and find the index of the currently checked one using .findIndex(); this way you can also easily check if any radio got checked at all:
var index = Array
.from(document.form1.button1)
.findIndex(function (current) {
return current.checked
})
if (index !== -1) {
console.log('Box ' + (index + 1) + ' is checked')
} else {
console.log('No box is checked')
}