TOC

This article is currently in the process of being translated into Portuguese (~32% done).

Forms:

Checkboxes

Quando desejamos mostrar opções que oferecem multipla escolha, podemos utilizar o elemento "Checkbox" (caixa de seleção). O checkbox é diferente do "radio", permitindo ao usuário selecionar multiplas opções, ao invés de apenas uma. A caixa de seleção é simplesmente um elemento input com a propriedade type ajustada para checkbox. Veja o exemplo abaixo:

<input type="checkbox">

No entanto, assim como em todos os elementos input, você precisa definir um name (nome) para que a caixa de seleção seja usável - sem um nome o elemento não será identificável ao enviar o formulário para processamento no servidor. Você também pode definir o value - esse será o valor enviado ao servidor se a caixa de seleção for marcada. Aqui está um exemplo:

<input type="checkbox" name="nameOfChoice" value="1">

Neste exemplo, se a caixa de seleção estiver marcada e o formulário for enviado ao servidor, o servidor será capaz de reconhecer o elemento "nameOfChoice" e seu valor será 1.

Marcado ou não?

Perceba que as caixas de seleção até agora não vieram marcadas desde o início - o usuário teria que interagir com a caixa de seleção para mudar seu estado de não marcado para marcado. Isso pode ser o que você quer, mas as vezes você quer que a caixa de seleção venha marcada por padrão, ou para sugerir uma opção ao usuário ou porque você está mostrando a caixa de seleção com um valor que corresponde a uma configuração existente no banco de dados, por exemplo. Felizmente, é bem simples - apenas adicione o atributo checked à caixa de seleção:

<input type="checkbox" name="nameOfChoice" value="1" checked>

Antigamente, com o uso do XHTML, em que cada atributo sempre deveria ter um valor, até mesmo os atributos booleanos (lógicos), o código ficaria assim:

<input type="checkbox" name="nameOfChoice" value="1" checked="checked" />

Ambas as formas funcionam em todos os navegadores modernos, mas a primeira forma é menor e mais ao estilo HTML5.

Múltiplas escolhas

So far, all our checkboxes have been simple switches, e.g. for defining whether an option is on or off. Checkboxes are great for that, but as mentioned, they can also be used to allow the user a selection of possible options. Let me show you a neat example where this makes sense:

<form method="post" action="/Tests/Post/">      
<fieldset>      
<legend>What is Your Favorite Pet?</legend>      
<input type="checkbox" name="favorite_pet" value="Cats">Cats<br>      
<input type="checkbox" name="favorite_pet" value="Dogs">Dogs<br>      
<input type="checkbox" name="favorite_pet" value="Birds">Birds<br>      
<br>      
<input type="submit" value="Submit now" />      
</fieldset>      
</form>

Notice how we now have multiple checkboxes, but they all share the same name ("favorite_pet") but different values (e.g. "Dogs"). When this form is submitted back to the server, all these checkboxes will be represented by a single name, but the value will be an array of 0-3 items. If you had used radio buttons instead of checkboxes, the user would only be allowed to pick a single favorite animal, but with checkboxes, they can select none of them, all of them or some of them.

Labels for checkboxes

If you tested the previous example, you will notice that we can put text next to a checkbox, but they are still two separate things - you can't click the text to trigger the checkbox. This can be really annoying for the user, but fortunately for us, it's easy to solve: Just use the label element! Here's a basic example to show you the difference:

<input type="checkbox" name="favorite_pet" value="Cats">Cats<br>  
<input type="checkbox" name="favorite_pet" value="Dogs" id="dogs">
<label for="dogs">Dogs</label><br>

Two checkboxes - one without a label and one with. They might look almost identical, but the one with the label can be triggered by clicking both the actual checkbox and the attached label. This is nice if you're sitting on a desktop PC with a mouse, but even better when you're using a touch device like a smartphone, where small checkboxes can be hard to hit with your finger.

The label is very simple - it uses the for attribute to attach itself to a form element with a matching id attribute (notice how I have "dogs" in both places).

Working dynamically with a checkbox

Just like any other DOM element, you are able to manipulate a checkbox using JavaScript. In that regard, it could be interesting to check whether a checkbox is checked or not and perhaps add some logic to control how many options a user can select. To show you how this can be done, I have extended a previous example (the "Favorite Pet" selector) to include some JavaScript magic:

<form method="post" action="/Tests/Post">  
<fieldset>  
<legend>What is Your Favorite Pet?</legend>  
<input type="checkbox" name="favorite_pet" value="Cats" onclick="return ValidatePetSelection();">Cats<br>  
<input type="checkbox" name="favorite_pet" value="Dogs" onclick="return ValidatePetSelection();">Dogs<br>  
<input type="checkbox" name="favorite_pet" value="Birds" onclick="return ValidatePetSelection();">Birds<br>  
<br>  
<input type="submit" value="Submit now">  
</fieldset>  
</form>  

<script type="text/javascript">  
function ValidatePetSelection()  
{  
var checkboxes = document.getElementsByName("favorite_pet");  
var numberOfCheckedItems = 0;  
for(var i = 0; i < checkboxes.length; i++)  
{  
if(checkboxes[i].checked)  
numberOfCheckedItems++;  
}  
if(numberOfCheckedItems > 2)  
{  
alert("You can't select more than two favorite pets!");  
return false;  
}  
}  
</script>

Allow me to quickly run through what this code does. We have the same form as before, but we have added an event handler to each of the checkboxes, which causes them to call a JavaScript function (ValidatePetSelection) when the user clicks them. In this function, we get a hold of all the relevant checkboxes using the getElementsByName function and then we loop through them to see if they are checked or not - for each checked item, we add to a number. This number is then checked and if it exceeds two, then we alert the user about the problem (only two pets can be selected) and then we return false. Returning false will prevent the checkbox from being checked.

This was just a simple example of how to work with checkboxes using JavaScript. You can do much more, especially if you use a JavaScript framework like jQuery, which will make it a lot easier to select and manipulate DOM elements.

Summary

Checkboxes allow you to setup selectable options for your users - either to toggle a single setting on or off, or to allow for multiple choices, like in the Favorite Pet example. You should use labels to tie your checkbox and the descriptive text together, to allow the user to click a larger area when manipulating the checkbox - this is also good for assisting technologies like screen readers for visually impaired.

This article has been fully translated into the following languages: Is your preferred language not on the list? Click here to help us translate this article into your language!