FDP checkbox hack (jquery)
by donabrams
HTML
<h2>form1</h2>
<form onsubmit="alert('BOOO!')">
A<input type="checkbox" name="a" value="a"/>
B<input type="checkbox" name="a" value="b" checked="checked"/>
C<input type="checkbox" name="a" value="c"/>
D<input type="checkbox" name="b" value="d"/>
E<input type="checkbox" name="b" value="e" checked="checked"/>
F<input type="checkbox" name="b" value="f"/>
<button type="submit">BOOOOO</button>
</form>
<h2>form2</h2>
<form>
A<input type="checkbox" name="a" value="a"/>
B<input type="checkbox" name="a" value="b" checked="checked"/>
C<input type="checkbox" name="a" value="c"/>
</form>
<h2>no form</h2>
A<input type="checkbox" name="b" value="a" checked="checked"/>
B<input type="checkbox" name="b" value="b"/>
C<input type="checkbox" name="b" value="c"/>
<p>This script scans for checkboxes and if any are found, adds a hidden field with the name '$NAME_combined' to the end of the containing form (or body if there is no containing form).</p>
<p>When any checkbox is clicked, the associated hidden field is updated with newline separated values of all checked checkboxes.</p>
<p>Checked boxes are immediately populated into hidden fields.</p>
JavaScript
$(function() {
// Takes any checkbox matching a name and consolidates them into one hidden field
// with '_combined' appended to it
// Optionally take a form in. If a form is provided, restrict this functionality to
// checkboxes within the forms
var updateCheckboxes = function(name, form) {
// s will be what the hidden field holds
var s = "";
// check for forms
if (form && form.length) {
form.find("input[type=checkbox][name=" + name + ']')
// for each checkbox
.each(function() {
var cb = $(this);
if (cb.attr("checked")) {
// append the value and a new line if its checked
s += cb.val() + "\n";
}
})
.end() //back up to the form
.find("input[type=hidden][name=" + name + '_combined]')
// set the value on the hidden field
.val(s);
}
else {
$("input[type=checkbox][name=" + name + ']')
// for each checkbox
.each(function() {
var cb = $(this);
if (cb.attr("checked") && cb.parents("form").length == 0) {
//append the value and a new line if its checked
s += cb.val() + "\n";
}
});
// set the value on the hidden field
$("body > input[type=hidden][name=" + name + '_combined]').val(s);
}
}
$("body").on("click", "input[type=checkbox][name]", function() {
var cb = $(this);
// get the name of the checkbox
var name = cb.attr("name");
// if this checkbox is in a form get it
var form = cb.parents("form").first();
updateCheckboxes(name, form);
});
(function() {
var names = {};
// blanks keeps track of teh hidden...