admin管理员组

文章数量:1399823

Like the title says, what's the best way in JavaScript to get all radio buttons on a page with a given name? Ultimately I will use this to determine which specific radio button is selected, so another way to phrase the question:

Given a string variable in JavaScript, how can I tell which exact radio button input element (if any) with that string as it's name is currently selected?

I'm not using jQuery. If you want to provide a jQuery answer, go ahead. Someone else might find it useful. But it won't help me and I won't upvote it.

Like the title says, what's the best way in JavaScript to get all radio buttons on a page with a given name? Ultimately I will use this to determine which specific radio button is selected, so another way to phrase the question:

Given a string variable in JavaScript, how can I tell which exact radio button input element (if any) with that string as it's name is currently selected?

I'm not using jQuery. If you want to provide a jQuery answer, go ahead. Someone else might find it useful. But it won't help me and I won't upvote it.

Share Improve this question edited Nov 5, 2009 at 19:56 Peter Mortensen 31.6k22 gold badges109 silver badges133 bronze badges asked Nov 5, 2009 at 19:29 Joel CoehoornJoel Coehoorn 415k114 gold badges577 silver badges813 bronze badges 3
  • I know it is. I've written about it at length: stackoverflow.com/questions/148670/… But it's not up to me. – Joel Coehoorn Commented Nov 5, 2009 at 20:00
  • 1 Wow, it's a good thing that link to Wikipedia/Javascript was added because I was totally clueless! – Josh Stodola Commented Nov 5, 2009 at 20:39
  • @Peter Mortensen: getting a little happy on the edit trigger there aren't ya? – Roatin Marth Commented Nov 5, 2009 at 21:25
Add a comment  | 

9 Answers 9

Reset to default 30

You can use document.getElementsByName(), passing the name of the radio group, then loop over them inspecting the checked attribute, e.g. something like:

function getCheckedValue( groupName ) {
    var radios = document.getElementsByName( groupName );
    for( i = 0; i < radios.length; i++ ) {
        if( radios[i].checked ) {
            return radios[i].value;
        }
    }
    return null;
}

getElementsByName didn't work for me. I did this:

    var radios = document.getElementsByTagName('input');
    for (i = 0; i < radios.length; i++) {
        if (radios[i].type == 'radio' && radios[i].checked) {
            nbchecked++;
        }
    }

Use document.getElementsByName() is the short answer to the question you asked.

However, it may be better to do something like this:

<form name="formFoo">
  Foo: <input type="radio" name="groupFoo" value="foo" checked> <br />
  Bar: <input type="radio" name="groupFoo" value="bar"> <br />
  Baz: <input type="radio" name="groupFoo" value="baz"> <br />
  <input type="submit" >
</form> 

Then use the JavaScript:

function getRadioValue(formName, groupName) {
    var radioGroup = document[formName][groupName];
    for (var i=0; i<radioGroup.length; i++)  {
       if (radioGroup[i].checked)  {
       return radioGroup[i].value;
       }
    }
    return null;
}

By doing this, you avoid having to use a function that searches the entire document. It just searches first for the form, then within that form for controls with that same name. The problem here is that if you were to have a checkbox in the middle of the form with the same name, it could be returned instead of the correct radio value. If another type of control was thrown in with the same name, then it could cause an error. Both of these circumstances should probably be considered programmer error, but it wouldn't hurt for the function to be expanded to check for them, at some potential performance loss. Just change the line:

       if (radioGroup[i].checked)  {

to:

       if (radioGroup[i].type=='radio' && radioGroup[i].checked)  {

I'll bite for the jQuery answer

var selectedValue = $("input[name='radio_name']:checked").val();
var options = document.getElementsByName('myRadioButtons');
for(i = 0; i < options.length; i++)
{
    var opt = options[i];
    if(opt.type=="radio")
    {              
        if(opt.checked)
        {
        }                  
    }
}
<form name="myForm" id="myForm" action="">  
<input type="radio" name="radioButton" value="c1">Choice 1
<input type="radio" name="radioButton" value="c2">Choice 2
</form>
<script>
var formElements = window.document.getElementById("myForm").elements;
var formElement;
var radioArray = [];

for (var i = 0, j = 0; i < formElements.length; i++) {
    formElement = formElements.item(i);
    if (formElement.type === "radio" && formElement.name === "radioButton") {
        radioArray[j] = formElement;
        ++j;
    }
}
alert(radioArray[0].value);
alert(radioArray[1].value);
</script>
$("input[type='radio'][name='xxxxx']:checked").val()

To get all radio buttons directly by name:

element.querySelectorAll("input[name='nameOfTheName']")

The querySelectorAll() method can be used to get elements of a certain type by name. There are advantages to using querySelectorAll compared to getElementsByName() in certain situations. If you use getElementsByName on anything other than document, you will get an error:

element_Name_Here.getElementsByName is not a function

But querySelectorAll() can be used on sub elements of the document. This is helpful when you want to get one element out of multiple elements that all have the same structure (Rows in a list). In that case, you might not want to try to give separate ID's to every row. In that situation, the function called can be passed this, get the parentNode and from the parent, search for a specific attribute. This avoids needing to search the entire document.

html

<div>
  <input type="radio" name="nameOfName" onchange="getOnlyThisRowsRadios(this)">
  <input type="radio" name="nameOfName" onchange="getOnlyThisRowsRadios(this)">
  <input type="radio" name="nameOfName" onchange="getOnlyThisRowsRadios(this)">
</div>
<div>
  <input type="radio" name="nameOfName" onchange="getOnlyThisRowsRadios(this)">
  <input type="radio" name="nameOfName" onchange="getOnlyThisRowsRadios(this)">
  <input type="radio" name="nameOfName" onchange="getOnlyThisRowsRadios(this)">
</div>
<div>
  <input type="radio" name="nameOfName" onchange="getOnlyThisRowsRadios(this)">
  <input type="radio" name="nameOfName" onchange="getOnlyThisRowsRadios(this)">
  <input type="radio" name="nameOfName" onchange="getOnlyThisRowsRadios(this)">
</div>
<div>
  <input type="radio" name="nameOfName" onchange="getOnlyThisRowsRadios(this)">
  <input type="radio" name="nameOfName" onchange="getOnlyThisRowsRadios(this)">
  <input type="radio" name="nameOfName" onchange="getOnlyThisRowsRadios(this)">
</div>

script

function getOnlyThisRowsRadios(thiz) {
  var i,L,parentElement,radioButtons;

  parentElement = thiz.parentNode;//Get the parent of the element
  radioButtons = parentElement.querySelectorAll("input[name='nameOfTheName']");
  console.log('radioButtons: ' + radioButtons)

  L = radioButtons.length;
  console.log('L: ' + L)

  for (i=0;i<L;i++) {
    console.log('radBttns[i].checked: ' + radBttns[i].checked)
    radBttns[i].checked = false;//Un-check all checked radios
  }

This definitely works if your name attribute is taken for something else.

var radios = document.getElementsByTagName('input');

 for (i = 0; i < radios.length; i++) {
    if (radios[i].type == 'radio' && radios[i].checked) {
console.log(radios[i])
    }
}

本文标签: In JavaScripthow can I get all radio buttons in the page with a given nameStack Overflow