Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In JavaScript, how can I get all radio buttons in the page with a given name?

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 image 870
Joel Coehoorn Avatar asked Nov 05 '09 19:11

Joel Coehoorn


People also ask

How do I select multiple radio buttons with the same name?

the name of the radio button defines the group it is in, then in the handler for the submitted form, you call the name to get the selected option. using line separators or divs will not disassociate them with each other. you can only have one radio button for a group selected.

How do I select a radio button when a label is clicked?

To select a radio button by clicking on its text in React:Add a label element for each radio button. The htmlFor prop of each label should be set to the id of each radio button. Click on the label element to select the radio button.

How can I know which radio button is selected via JavaScript?

Use document. getElementById('id'). checked method to check whether the element with selected id is check or not. If it is checked then display its corresponding result otherwise check the next statement.

How do I group radio buttons in JavaScript?

Use the <input> element with the type radio to create a radio button. Assign a name to multiple radio buttons to form a radio group. Only one radio button in the group can be selected. If the radio button is selected, its checked property is true .


2 Answers

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;
}
like image 116
Rob Avatar answered Oct 05 '22 23:10

Rob


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++;
        }
    }
like image 36
Robin Avatar answered Oct 06 '22 00:10

Robin