简体   繁体   中英

Selecting Radio Buttons from Links

I am learning javascript from the "Javascript in 10 steps on less" book. On task 90 where the task is selecting radio buttons from the link,i tried the code as exactly in book. There is the error that "TypeError: document.myForm.myRadio is not a function". My code is as follows:

<script language="JavaScript">
function selectButton(button) {
    document.myForm.myRadio(button).checked = true;
}
</script>
<form name="myForm">
    <input type="radio" name="myRadio" value="First Button" /> Button 1<br>
    <input type="radio" name="myRadio" value="Second Button" /> Button 2
</form>
<a href="#" onClick="selectButton(0);">Select First Radio Button</a><br>
<a href="#" onClick="selectButton(1);">Select Second Radio Button</a>

I myself see no error in the code. Anyone help me point out the error.

There:

function selectButton(button)...

you are passing button as an argument to the function selectButton . Using () in this case is correct.

But there:

document.myForm.myRadio(button).checked = true;

myRadio is array of buttons. Indexes in arrays are accessed using [] syntax.

So it should be

document.myForm.myRadio[button].checked = true;

Demo:

 <script language="JavaScript"> function selectButton(button) { document.myForm.myRadio[button].checked = true; } </script> <form name="myForm"> <input type="radio" name="myRadio" value="First Button"> Button 1<br> <input type="radio" name="myRadio" value="Second Button"> Button 2 </form> <a href="#" onClick="selectButton(0);">Select First Radio Button</a><br> <a href="#" onClick="selectButton(1);">Select Second Radio Button</a> 

You code is correct but use [] bracket instead of () like:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
</head>
<body>
 <script language="JavaScript">
function selectButton(button) {
document.myForm.myRadio[button].checked = true;
}
</script>
<form name="myForm">
<input type="radio" name="myRadio"
value="First Button"> Button 1<br>
<input type="radio" name="myRadio"
value="Second Button"> Button 2
</form>
 <a href="#" onClick="selectButton(0);">Select First
 Radio Button</a><br>
 <a href="#" onClick="selectButton(1);">Select Second
 Radio Button</a>
</body>
</html>

FIDDLE DEMO

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM