Why The Javascript Result Always Return First Value?
Solution 1:
Each radio button is an element in its own right. The radio group is not a single element.
Every radio button has the same id, which is invalid and not allowed in HTML.
When you getElementById
, the browser attempts to perform error recovery and gets the first element with that id (ignoring the others).
If you want to deal with a group of elements, then:
- make them members of a class
getElementsByClassName
- Loop over the result and test the
checked
property - When you find a true
checked
take thevalue
of that element
Solution 2:
Your radiobuttons have the same id
123. You are selecting the element from the DOM using this id. Make sure every radiobutton has a unique id.
You don't even need the Id if you pass the element to the function.
HTML:
onClick='return showBox1(this)'
JavaScript
function showBox1(element){
confirm (element.value);
}
Solution 3:
First of all, all the radio buttons have the same id attributes: "123".
The document.getElementById() function expects, that a certain id is only present once on a page.
If you want to get the selected value for the elements with id "123", then you should select like this:
var test = document.querySelector("#123:checked")[0].value;
If this doesn't work, then try:
var test = document.querySelector("[id=\"123\"]:checked")[0].value;
Post a Comment for "Why The Javascript Result Always Return First Value?"