I was trying to get selected radio button by using "document.getElementByName('nameOfradio')" because all of the radio buttons share the same name. But, nothing happened. I tried the same thing with document.getElementById('nameOfradio') and worked well.However, I had to give unique id for all of the radio buttons. So that, it turns ugly when i have 20 radio buttons. As a result, what I wanted is making a shortcut. How can i get the value of selected radio button by using their "name"? Codes;
Html
<input type="radio" name="nameOfradio" value="onm1" /> 1
<input type="radio" name="nameOfradio" value="onm2" /> 2
<input type='button' onclick='radio3()' value='Submit' />
</form>
Ajax(relavant part of radio3())
var radioPushed = document.getElementByName('nameOfradio').value;
var queryString = "?radioPushed=" + radioPushed;//to send the value to another file
ajaxRequest.open("GET", "radio_display.php" + queryString, true);
ajaxRequest.send(null);
As i said document.getElementById worked but it requires too much work:( How can i make it simplier by using common feature of radio buttons, instead of giving them unique id? A short explanation why i could not make it would be very helpful(new in javascript and ajax)
Using Input Radio checked property: The Input Radio checked property is used to return the checked status of an Input Radio Button. Use document. getElementById('id'). checked method to check whether the element with selected id is check or not.
The checked selector is used to select all checked elements in input tag and radio buttons. This selector is used with radio buttons, checkbox and option elements. Example 1: html.
Radio buttons allow only one choice within a group of buttons. Each radio button within a group should have the same name. You can create more than one group of radio buttons by using different names.
document.querySelector('input[name=nameOfRadio]:checked').value
Eg:-
<form>
<input type="radio" name="gender" value="male"> Male<br>
<input type="radio" name="gender" value="female"> Female<br>
<input type="radio" name="gender" value="other"> Other
</form>
document.querySelector('input[name=gender]:checked').value
Also, you can add a checked
attribute to a default radio button among the group of radio buttons if needed
<input type="radio" name="gender" value="male" checked> Male<br>
<input type="radio" name="gender" value="female"> Female<br>
<input type="radio" name="gender" value="other"> Other
This line:
document.getElementByName('nameOfradio').value
should be:
document.querySelector('input[name=nameOfradio]:checked').value;
using querySelector
Note that CSS pseudo-classes are accessed by a colon (:).
Joe's answer should be the accepted answer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With