Bulknews::Subtech RSSフィード

2008/10/01 (水)

[jQuery] Unbreak checkboxes 05:52  [jQuery] Unbreak checkboxes - Bulknews::Subtech を含むブックマーク はてなブックマーク -  [jQuery] Unbreak checkboxes - Bulknews::Subtech

Checkbox is a painful HTML element.

If you have a dynamically generated form that has checkboxes, the backend app has no way to tell if a) there's a checkbox that is unchecked or b) there was no checkbox at all. For instance,

<input type="checkbox" name="a" /> A
<input type="checkbox" name="b" value="1" /> B

If you check 'A' and uncheck 'B', the parameters you get is "a=on". You can't tell if the checkbox 'B' was there but unchecked or there wasn't checkbox 'B' present from the beginning.

The following code fixes the situation. It traverses the input type="checkbox" fields on form.submit, and adds name=off (or name=0 if the input element has some value).

$( function() { 
    var form = $(this);
      if(!this.checked) {
        var input = document.createElement("input");
        var value = this.value == '' ? 'off' : '0';
        $(input).attr({ type: "hidden", name: this.name, value: value });

This way you'll get 'a=on&b=0' or 'a=off&b=1' if you check A or B and uncheck the other respectively.