Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript selected radio

I want to check what is the selected radio input.

here is my code.

<input name="u_type" type="radio" value="staff" id="u_type" checked="checked" /> Staff
<input name="u_type" type="radio" value="admin" id="u_type" /> Admin
<input id="add_user" name="add_user" type="button" onclick="addUser();"  value="Add" class="submitButton admin_add" />

function addUser()
{
//how to check what is the selected radio input
}

thanks.

like image 890
Sasindu H Avatar asked Jun 30 '11 10:06

Sasindu H


People also ask

How do I know if my input radio is selected?

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.

What value does a radio button return?

The value property sets or returns the value of the value attribute of the radio button. For radio buttons, the contents of the value property do not appear in the user interface. The value property only has meaning when submitting a form.


2 Answers

function addUser() {
    //how to check what is the selected radio input
    alert(getCheckedRadioValue('u_type'));
}

function getCheckedRadioValue(name) {
    var elements = document.getElementsByName(name);

    for (var i=0, len=elements.length; i<len; ++i)
        if (elements[i].checked) return elements[i].value;
}

And element's IDs must be different.

like image 114
Roman Sklyarov Avatar answered Oct 21 '22 19:10

Roman Sklyarov


To get the value of the checked radio button, without jQuery:

var radios = document.getElementsByName("u_type");
for(var i = 0; i < radios.length; i++) {
    if(radios[i].checked) selectedValue = radios[i].value;   
}

(assuming that selectedValue is a variable declared elsewhere)

like image 32
James Allardice Avatar answered Oct 21 '22 18:10

James Allardice