javascript selected radio

99封情书 提交于 2019-11-26 21:16:08

问题


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.


回答1:


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.




回答2:


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)




回答3:


$('input[name=u_type]:checked').val()

will get you the value of the selected option which you can, of course, assign to a variable. Due to admonishment, I should also point out that this is jquery, a handy javascript library for making DOM manipulation easier and with excellent cross-browser compatibility. It can be found here.




回答4:


Alternatively to kmb385's suggestion you could wrap your inputs in a form, and make sure all of the input names are different (you have two u_type) names.

Then you can access the inputs as document.formname.inputname.checked, which will return true or false.




回答5:


I know this is an old question, but the answers given seem overly complex.

As pointed out earlier, you should not have two elements with the same id. That violates the html spec. Just remove the id attributes, or make them two different values. Then simply use this to get the checked value:

document.querySelector("input[type='radio'][name='u_type']:checked").value




回答6:


You shouldn't have two radio elements with the same id. You need to change one of the ids then check both radio buttons like:

if(document.getElementById("u_type").checked == true)
{
   //do something
}

I would recommend using jquery to do this instead of native js.




回答7:


The following is the jQuery implementation to get the value of a radio button

$("#u_type").click(function() {
var value = $(this).val();
});

If you want to use javascript, then:

function get_radio_value()
{
for (var i=0; i < document.form.u_type.length; i++)
{
   if (document.form.u_type[i].checked)
   {
   var val = document.form.u_type[i].value;
   }
  }
}


来源:https://stackoverflow.com/questions/6533138/javascript-selected-radio

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!