[Solution]: element access problem when only a single radio button defined

Kor's AvatarKor: When you have a single radio button, the classical reference return, logically, a single element, not a collection. A single element has no length property. For instance, give a textbox a name, than try to find its length property. You will get undefined, logically. Same with a single radio button.

DOM method getElementsByName() returns always a collection, thus this is the reason for DOM method works, classical form’s elements reference don’t.

once again: getElementsByName() returns always a collection, thus it has always a length property, very much alike an array. Now if you have a single element with a certain name refered by getElementsByName() it is the same as you would have an array with a single element.

This is the reason for you need always an index when using getElementsByName() to refer a certain element.

Classical reference

Code:
document.formname.elementname

is ambiguous. It returns a collection if there are more than one element, but it returns the element itself when there is no other element with the same name.

Code:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="en">
<head>
<title>Radion Test</title>
<script language="javascript" type="text/javascript">
function radio_test(){
     var str= "1. document.forms['dummy'].elements['single'].length=\n\t"+
     document.forms.dummy.elements.single.length+
     "\n\n2. document.forms['dummy'].elements['single'].type=\n\t"+
     document.forms.dummy.elements.single.type+
     "\n\n3. document.getElementsByName('single').length=\n\t"+
     document.getElementsByName('single').length+
     "\n\n4. document.getElementsByName('single')[0].type=\n\t"+
     document.getElementsByName('single')[0].type;
     alert(str);

     return false;
}
onload=function(){
document.getElementsByName('submit')[0].onclick=radio_test;
}
</script>
</head>
<body>
<form name="dummy" action="" onsubmit= "return false">
        <fieldset><input type="radio" name="single" >
        <input type="submit" value="submit" name="submit">
        </fieldset>
</form>
</body>
</html>

Quoted: http://www.webdeveloper.com/forum/showthread.php?t=184376

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s