Reputation: 139
In the javascript, I have the pointer to get the name of the fruit. But the alert always shows null. I checked my logic but unable to find the problem. Any suggestions? thanks!
<!DOCTYPE html>
<html>
<head>
<title>My Fruit</title>
<script type="text/javascript">
function checkFruit(){
var fruit_radio_pointers = document.querySelector('[name="fruit"]');
var which_fruit = null;
for(var i=0; i<fruit_radio_pointers.length; i++){
if(fruit_radio_pointers[i].checked){
which_fruit = fruit_radio_pointers[i].value;
break;
}
}
alert(which_fruit);
}
//document.getElementById("my_btn").addEventListener("click", checkFruit, false);
</script>
</head>
<body>
<p>
<input name="fruit" type="radio" value="apple" /> Apple<br />
<input name="fruit" type="radio" value="cherry" /> Cherry
</p>
<p>
<button id="my_btn" onclick="checkFruit()" >Which Fruit?</button>
</p>
</body>
</html>
Upvotes: 0
Views: 1100
Reputation: 6052
Use querySelectorAll
:
var fruit_radio_pointers = document.querySelectorAll('[name="fruit"]');
querySelector
only returns the first found match (not as an array).
It is equal to document.querySelectorAll('[name="fruit"]')[0]
.
As you may have figured out, querySelectorAll
returns all of the found matches as an array.
Upvotes: 4