Jump to content

Radiobutton and Checkbox validation


AngelicOne
 Share

Recommended Posts

I know that there are lots of tutorials out there how to do this. Almost all of it suggests to check each element like this.

if(document.form.radio[0].checked == false && document.form.radio[1].checked == false){//code}

The above code works just fine but I preferred loop instead like this.

for(i++; i <= document.form.radio.length; i++){if (document.form.radio[i].checked == false){//code}}

The loop I used works but I'm not comfortable with it. Why? The code inside the if statement runs multiple times depending on the length of the radiobutton. So if I have three radio buttons, the code will run 3 times and alert msg will show 3x. To fix this, I used a break statement. I'm not comfortable on using break statement. Could someone please tell me other options using loop through radiobutton?EDIT:I noticed that even I checked on radiobutton it runs the code inside the if statement. I'm confused. :)

Edited by AngelicOne
Link to comment
Share on other sites

First of all, ditch the old dot notation (the document.form.radio stuff). There are better ways to access those elements, like getElementsByTagName and getElementsByName. Look up those two functions and try to get something working with one of them. I would probably suggest getElementsByName.As to the issue at hand,Of course it's going to run the code for each radio. What exactly is it you're trying to do? Why don't you want it to run over each radio?

Link to comment
Share on other sites

since only one radio button can be checked at once, if the loop is setup correctly, it will 'run' three times to iterate over all the radios, but the code should only execute once since only one can be true (while the rest will be false). If you want to be able to select multiple options from a group, perhaps you want to use checkboxes? Either way, you should implement a different method for obtaining the elements first (as SM suggested), and then take it from there.

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...