开发者

How to access radioButton individual items?

开发者 https://www.devze.com 2022-12-23 17:30 出处:网络
I\'ve got 2 radio button groups showed differently depending on the value selected on another radio button. The thing is that I would like to set the default value of the group to the first element in

I've got 2 radio button groups showed differently depending on the value selected on another radio button. The thing is that I would like to set the default value of the group to the first element in the radiobutton group, but when I change from the other radio button it preserves the value previously selected, when I want it to be reset to the default value.

I've been searching in the javascript repository but apparently I cannot access like it says with radio[1].checked = true... It says that radio[1] is undefined, but radio is an HTML Input element object. I'm accessing it from a different file, but var radio = docu开发者_开发问答ment.getElementById("radio") works, but I can't access the individual radiobuttons.

Thank you in advance


You can access them if you give each radiobutton an individual ID. The "name" attribute defines the group.


I agree with Robusto that you should give your radio elements ID attributes, and reference them that way.

However, you can also access the form.elements[] array, and access your radio button values that way:

for( i = 0; i < document.formname.elements.length; i++ ) {
  if(document.formname.elements[i].type == "radio") {
    document.formname.elements[i].checked = true;
  }
}


You can access them the way you describe:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head><title></title>
</head>
<body>

<form action="" method="get">
    <input type="radio" name="foo" value="One">
    <input type="radio" name="foo" value="Two">
    <input type="button" value="Show info" onclick="showInfo()">
</form>

<script type="text/javascript"><!--
function showInfo(){
    var info = "";
    for(var i=0, len=document.forms[0].foo.length; i<len; i++){
        info += "Radio button " + document.forms[0].foo[i].name + " is " + (document.forms[0].foo[i].checked ? "checked" : "not checked") + " and has a value of '" + document.forms[0].foo[i].value + "'\n";
    }
    alert(info);
}
//--></script>

</body>
</html>


If you want to refer to a specific radio button in the group, using the id attribute as per Robusto's answer is the way to go about it. However, if you want to do something with each of the radio buttons in the group, you could use getElementsByName, which returns a collection of all elements found with the given name:

var radio_buttons = document.getElementsByName("radio");
for (var i = 0; i < radio_buttons.length; i++)
{
  // do something with radio_buttons[i]
}
0

精彩评论

暂无评论...
验证码 换一张
取 消