Forum Moderators: open

Message Too Old, No Replies

elements array

arrays

         

bbm_builder

5:31 pm on Feb 9, 2006 (gmt 0)

10+ Year Member



This is probably a simple issue and reflects my inexperience, but I am having a very difficult time debugging a very simple program containing a form using radio buttons and the elements array in Javascript. I will list the script I am using below, if anyone can help I would be very grateful. BTW, the message I am getting is "element is undefined"

<head>
<script language=Javascript><!---

function testIt() {
with(document.test_radio) {

if (element[0].checked) {
alert ("You selected yes");
}
else {
alert ("You selected no");
}
}

}


//--></script>

</head>

<body>

<form name="test_radio">
<input type ="radio" name="answer" value=yes><b>Yes</b><br><br>
<input type="radio" name="answer" value=no><b>No</b><br><br>
<input type="button" name="button" value="Submit" onclick="testIt()">
</form>

<form action="http://mydomain.com/cgi-bin/radio_test.cgi"
method="post" name="imlearning">

<input type="hidden" name=info value="">
</form>

Bernard Marx

6:09 pm on Feb 9, 2006 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



This is probably a simple issue

elements

(BTW: If they don't select anything, they are still getting "No".)

I'd avoid using

with
for a while, it can be unpredictable.

rocknbil

8:33 pm on Feb 9, 2006 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Yes but one of the radio buttons in an array should always load checked.

I notice you have two forms there. Instead of the with, you can pass the form object to the routine. This would allow you to use the routine from any form and you don't need to reference the form specifically by name:

<head>
<script type="text/javascript">

function testIt(form) {

//for (i=0;i<form.elements.length;i++) {
//alert(form.elements[i].name);
//}

if (form.elements[0].checked) {
alert ("You selected yes");
}
else {
alert ("You selected no");
}

}
</script>

</head>

<body>

<form name="test_radio" onSubmit="return false;">
<input type ="radio" name="answer" value="yes"><b>Yes</b><br><br>
<input type="radio" name="answer" value="no" checked><b>No</b><br><br>
<input type="submit" name="button" value="Submit" onclick="testIt(this.form);">
</form>

A few notes:
- if you quote one, quote them all
- "script language" is deprecated
- use type=submit with return false in form onSubmit so if Javascript is disabled, the form will still submit
- Uncomment my little for... loop to read in all elements in the passed form. Helpful little debugging thingy.

bbm_builder

10:35 pm on Feb 9, 2006 (gmt 0)

10+ Year Member



Thank you so much for your help.