views:

48

answers:

1
+1  Q: 

Checkbox validator

I have a list of checkboxes and I would want to make sure that the user will check at least one before submitting the form. How can I do this?

There are 3 categories then 10 items under each category with a checkbox.

I'm thinking of doing this in javascript wherein I will have a hidden variable then when the user will check any of the checkboxes, the hidden variable will have 1 as its value then if the user will uncheck the box, the hidden variable will have 0 as its value.

+3  A: 

How are you marking them up?

I hope like this...

<input type="checkbox" name="something[]" value="55" />

Then in PHP...

if ( ! isset($_POST['something']) OR empty($_POST['something'])) {
   echo 'Select a checkbox, please!';
}

You can also check with JavaScript...

var inputs = document.getElementById('my-form').getElementsByTagName('input');
var checked = 0;
for (var i = 0, length = inputs.length; i < length; i++) {
    if (inputs[i].getAttribute('type') !== 'checkbox') {
       continue;
    }

    if (inputs[i].checked) {
        checked++;
    }
}

if (checked === 0) {
   alert('Select a checkbox, please!');
}

See it working on JSbin.

alex
how can I do this in javascript please?
anonymous2
@anonymous2 See my edit :)
alex
LeonixSolutions
@LeonixSolutions If that comment was addressed to me, then I'll say "as a convenience for the end user, I validate with JavaScript. For integrity of my application, I validate on the server."
alex
There's an error: Missing Variable Name: for (var i = 0, var length = inputs.length; i < length; i++) {\n
anonymous2
@anonymous2 Whoops, working on it, check it again in a moment.
alex
LeonixSolutions
@LeonixSolutions 1) You should design everything to work without JS - or at least not fail. 2) It is easier for the end user to be told their input did not validate *without* waiting for a round trip to the server. Plus, why bother sending it on if we know it is invalid already - your host will thank you :)
alex
+1 for the comments alex. I totally agree with what you said. :)
BrunoLM
Alex, while I agree with you, there is a lot of duplicated effort there. I just wonder if you are always allowed the luxury of it in a commercial environment ... I can hear management now, "so, you have to validate server side in case js is off? so why validate client side too?". I do understand what you are saying, just wonder if it will always be permitted in commercial projects (hmm, how do you ensure that your client side one minor discrepancy and ...)
LeonixSolutions
@LeonixSolutions It can be a PITA, especially when needing to pass back rules from PHP to JS to ensure consistency. I don't ask in my environment, I just generally do it. With jQuery and the Validation library, the effort is quite small and worth doing.
alex