Radio Button Question with Javascript

A

amerar

Hi All,

I am using this code to dynamically check is a radio button was checked
on the page. This worked great, if there is more then 1 button in the
group, but fails if there is only 1 button in the group......

Can anyone help debug? I'm stumped.....

function valButton(btn) {;
var cnt = -1;;
for (var i=btn.length-1; i > -1; i--) {;
if (btn.checked) {cnt = i; i = -1;};
};
if (cnt > -1) {return btn[cnt].value;};
else {return null;};
};


Thanks,
 
L

Lee

(e-mail address removed) said:
I am using this code to dynamically check is a radio button was checked
on the page. This worked great, if there is more then 1 button in the
group, but fails if there is only 1 button in the group......

Why would there be one button in a radio group?
Change the page that generates the form to eliminate the button or at least
change it to a checkbox if there's only one.
Can anyone help debug? I'm stumped.....

function valButton(btn) {;
var cnt = -1;;
for (var i=btn.length-1;

The problem is that if there is only one member, btn does not have a "length"
attribute.
 
R

RobG

Fixed it.....I put in a hidden button, just to force it to always be
2........

And now you have a hidden trap for unwary maintainers of you page. Why
not test to see what btn is and deal with it appropriately?

function valButton(btn)
{
var len = btn.length;
if ('number' == typeof len) {
for (var i=0; i<len; ++i) {
if (btn.checked) return btn.value;
}
return null;
}
return (btn.checked)? btn.value : null;
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,432
Messages
2,571,681
Members
48,796
Latest member
Greg L.

Latest Threads

Top