jeudi 28 janvier 2016

How to submit a checkbox only when it is checked, only unchecked and both when checked or unchecked

There are 3 possible behaviours someone might want from a input[type="checkbox"]

  1. submit value when input[type="checkbox"]:checked,
  2. submit value when input[type="checkbox"]:not(:checked)
  3. submit value when input[type="checkbox"] checked or unchecked

1. Submit when checked

This is the behaviour most people would want which is lucky because this is the elements default behaviour.

2. Opposite submit when unchecked use case

Assume you created a form with all fields checked by default

<input type="checkbox" checked value="1" name="1" />Check me if Yes
<input type="checkbox" checked value="1" name="2" />Check me if Yes
...
...
<input type="checkbox" checked value="1" name="49" />Check me if Yes
<input type="checkbox" checked value="1" name="50" />Check me if Yes

we created the form so we know the default values.

It would make sense to submit and process(server) only the changed values. In this case its the unchecked checkboxes.

This is alternative of using a double negative and submitting normally.

<input type="checkbox" value="0" name="1" />Check me if No
<input type="checkbox" value="0" name="2" />Check me if No
...
...
<input type="checkbox" value="0" name="49" />Check me if No
<input type="checkbox" value="0" name="50" />Check me if No

3. Submit when checked or unchecked

This might be used if there were two possible values you might want to send to the server.

<input type="checkbox" default="NO" value="YES" />Check me if YES

Number 1. is pretty straight forward but believe it or not this is a question on stackoverflow.

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

So how to achieve the other two?




Aucun commentaire:

Enregistrer un commentaire