PDA

View Full Version : Required Field should (but is not) triggering an alert



kuau
12-08-2009, 04:21 AM
I hope someone can see what I cannot. This should be so simple. I have a form to which I have applied some simple Javascript validation to make required fields. It works perfectly for 12 of the fields but I can't get it to work on the last field. The only difference is that for the first 12 fields I am checking to see if the text field is blank, whereas the last field is a radio button with 2 choices: Yes or No, so I am checking if the value is "No" or not.

The Javascript is:


function validate() {
if (document.infoform.agreed.value == "No") {
alert("You MUST agree to our Terms.");
return false;
}
return true;
}

The form code is:


I agree <input type="radio" name="agreed" value="No" checked> No <input type="radio" name="agreed" value="Yes"> Yes

I load the results into a table and when No is checked it does load "No". This is driving me nuts. If I use == "No" it gives no alert. If I use != "Yes" it gives an alert no matter what is checked.

Please help! Thanks, e :)

vwphillips
12-08-2009, 10:30 AM
<!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" xml:lang="en" lang="en">

<head>
<title></title>
<script type="text/javascript">
/*<![CDATA[*/

function Test(){
var frm=document.forms[0];
var rads=frm['agreed'];
for (var mess='Please Select 1',z0=0;z0<rads.length;z0++){
if (rads[z0].checked){
mess=rads[z0].value=='Yes'?false:'You do not agree';
break;
}
}
if (mess){
alert(mess);
return false;
}
return true
}
/*]]>*/
</script></head>

<body>
<form>
I agree <input type="radio" name="agreed" value="No" checked> No <input type="radio" name="agreed" value="Yes"> Yes

<input type="button" name="" value="TEST" onclick="Test();"/>
</form>

</body>

</html>

kuau
12-08-2009, 09:22 PM
Dear Vic:

I really appreciate your trying to help, but you totally lost me. I already have a function that applies to 12 other cases and would rather not go backwards to where I have no clue how it works. What is rads?? What is z0?? No clue.

Could you please just tell me what is wrong with my little function above? At least I understand the logic and don't have to learn Swahili.

Thanks! :)

kuau
12-08-2009, 11:13 PM
I figured it out! All I had to put was checked == false instead of value == "No"

I knew it was something simple. :)

bluewalrus
12-09-2009, 12:01 AM
This also works


function validate() {
for (var i=0; i < 2; i++) {
if (document.infoform.agreed[i].checked) {
var agreed = document.infoform.agreed[i].value;
}
}
if (agreed == "No") {
alert("You MUST agree to our Terms.");
return false;
}
return true;
}