anhtran
anhtran

Reputation: 2044

HTML5 - Select multi required-checkbox

I've writen some code here: http://jsfiddle.net/anhtran/kXsj9/8/

Users have to select at least 1 option on the group. But it makes me must click all of them to submit the form. How to do this issue without javascript?

Thanks for any help :)

Upvotes: 4

Views: 7622

Answers (4)

james.garriss
james.garriss

Reputation: 13397

The ideal answer would be to use HTML5 and the required attribute as part of a select element, like so:

<form method="post" action="processForm.php">
    <label for="myLanguages">What languages can you program in?</label>
    <br>
    <select id="myLanguages" multiple required>
        <option value="C#">C#
        <option value="Java">Java
        <option value="PHP">PHP
        <option value="Perl">Perl
        <option value="Haskell">Haskell
    </select>
    <br>
    <input type="submit" value="Submit">
</form>

Yes, I know they are not checkboxes, but the end functionality is exactly what you want. Sadly, neither IE 9 nor Safari 5 currently have support for the required attribute. Chrome 13 and FF 5, however, do. (Tested on Win 7)

Upvotes: 2

Niklas
Niklas

Reputation: 30002

I thought it'd be possible, to do in part, what you were after using CSS. Not using the required attribute but to instead hide the submit button if nothing was selected.

You'd get rid of the required attributes and use CSS similar to this:

input[type=submit] {
    display:none;
}

input[type=checkbox]:checked ~ input[type=submit] {
    display:block;
}

However, that particular CSS is not working on my version of Google Chrome. I've made a question regarding it here. It seems to be working fine on my FF 3.6 though.

Upvotes: 1

Pedro Correia
Pedro Correia

Reputation: 813

You can't do this without javascript. What you can do is select a default option and set it as selected. But it can't assure you that a checkbox is selected when the form is submitted.

Upvotes: 0

Marty
Marty

Reputation: 2963

I think this html5 attribute is only supposed to define which fields are required. You cant put logic in to say "at least one is required".

You will need to add custom javascript for this to work (and/or have validation on the server side).

hope this helps...

Upvotes: 2

Related Questions