Required for Checkbox / HTML5

Asked

Viewed 4,189 times

2

I have several input fields from checkbox referring to the interests of the customer to mark (Interest 1, 2, 3, ...), and another with option of All.

I want him to be forced to mark one of these camps,

If I put required in a specific field, I force him to mark a field that would be optional.

So I can’t put required in no input.

In this case the form will be Submit without him scoring any, I wanted to compel him to at least score some.

If I put radio, the problem is that he can only choose one option, but there are several that you can choose.

Would you have any solution to solve this without the use of Javascript, only with the HTML5 such as the required ?

2 answers

5


I think only with HTML this is not possible. That is, as you explained in the question, you cannot use the required because it will force you to check inputs that are not mandatory.

You really have to use Javascript.

Suggestion:

HTML

<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<button type="button">Testar</button>

Javascript

var inputs = document.querySelectorAll('input');

function verificar() {
    return [].filter.call(inputs, function (input) {
        return input.checked;
    }).length;
}
document.querySelector('button').addEventListener('click', function () {
    var valido = verificar();
    if (!valido) alert('Falta escolher uma checkbox!');
    else alert('Tudo ok!');
});

jsFiddle: http://jsfiddle.net/puLhypmd/

  • Thank you! I’ll do as you said.

  • @Andrésilveiramachado I am glad to have helped. I think the question is good and it would be very interesting to have required for fieldset or group but I think it’s gonna be a while.

0

Java Script is an option to do this validation in the Front-end, if you are using some programming language as Php could also do the validation by the Back-end. Only with HTML the only option would be to put the checked attribute. Example:

<input type="checkbox" name="development" value="development"checked> Development<br>
<input type="checkbox" name="database" value="database"> Database<br>
<input type="checkbox" name="network" value="network"> Network<br>

The checked attribute used in an input, sets this input as selected by default. Thus this option would be selected by default in your form and when capturing the value of this input would be received the value of that input, which in the above example is 'Development'. The other fields would come as null by default in the example or if the user selects them (ie mark them, the input receive the 'checked'), will capture the information as well. I hope I’ve helped.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.