Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
The moose likes HTML, CSS and JavaScript and the fly likes how to know checkbox is selected? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Engineering » HTML, CSS and JavaScript
Bookmark "how to know checkbox is selected?" Watch "how to know checkbox is selected?" New topic

how to know checkbox is selected?

Murad Iqbal
Ranch Hand

Joined: Dec 09, 2003
Posts: 90
Hi all, I need to do a validation check before submittion my jsp data to the servlet. I need to ensure that at least one checkbox of the checkbox array is selected. Kindly inform how to do this. I am using the following method but to no avail.

for (int i=0;i<n;i++)
boolFlag = true;
Pedro Penna
Ranch Hand

Joined: Jun 05, 2004
Posts: 46
This is client-side scripting. Try this:

Yuriy Fuksenko
Ranch Hand

Joined: Feb 02, 2001
Posts: 413[i].checked

Murad, that line only make sense, if all your checkboxes have the same name.
Otherwise there are 2 choices:

1. You can have a function, that goes through your checkboxes right before submitting a form, and checks does any selected. This is exactly what Pedro example is about. I wrote another version of the same function, that stops if the next element in the sequence does not exist, and therefor doesnot need to know how many checkboxes you have.

2. You actually have another choice here. Let say you have a variable, that will be incremented, when any checkbox checked and decremnted when it is unchecked. Than before form submitting you only need to test is that variable greater than zero or not. Good thing about it - it does not care about your naming patterns and how many elements you got.
I agree. Here's the link:
subject: how to know checkbox is selected?
jQuery in Action, 3rd edition