PDA

View Full Version : Radio Button Validation


beautyfiend
07-07-2009, 05:05 PM
Hi,
This is doing my head in, I don't know what is wrong with my code but my radio button validation is not working.:(
I think maybe the 'card.length? I checked for errors on PSPad and nothing came up...
Any help greatly appreciated!


cardcheck= -1;
for (i=myform.card.length -1; i > -1; i-) {
if (myform.card[i].checked) {
cardcheck = i; i= -1;
}
}
if (cardcheck == -1 {
alert ("Must select Card Type");
return false;
}

And:
Visa<input type="radio" name="card" value="Visa">
<br /><br />
Amex <input type="radio" name="card" value="Amex">
<br /><br />
Mastercard <input type="radio" name="card" value="Mastercard">
<br /><br />

yell0wdart
07-07-2009, 06:49 PM
OK, I think this code has some big problems. It's probably not even running without errors in the browser (using the error console or FireBug would tell you this). ;)


// Remember to declare your variables with the keyword 'var'
cardcheck= -1;

// White space is your friend. Use it to make your code more readable

// Your for loop's incrementor (i) isn't being incremented or decremented.
// You'll want to use i++ or i-- here, not i-
for (i=myform.card.length -1; i > -1; i-)
{
if (myform.card[i].checked)
{
cardcheck = i;

i= -1;
// NEVER, under any circumstances, change the value of your
// counter in a for loop. Use the 'break' keyword instead if
// you need to exit a loop.
}
}

// You're missing a closing ')' here
if (cardcheck == -1
{
alert ("Must select Card Type");
return false;
}


You're probably wanting something more along these lines:


var cardcheck = -1;

for (var i = 0; i < myform.card.length; i++)
{
if (myform.card[i].checked)
{
cardcheck = i;
break;
}
}

if (cardcheck == -1)
{
alert ("Must select Card Type");
return false;
}

beautyfiend
07-08-2009, 01:25 PM
Thanks for all your help, much appreciated! You must be a pro.
I will use firebug from now.Thanks.

yell0wdart
07-08-2009, 04:01 PM
You're very welcome. :)