I have a PHP script that dynamically creates a HTML page with a form and a lot of checkboxes in it. After hitting the Submit-button the form is send to another PHP script that needs to figure out which checkboxes are checked. For this, the HTML code for every checkbox looks something like this..
<input type="checkbox" name="id[]" value="(the id goes here)" />
(notice that the checkboxes form an array)
The actual problem is that I wan't to do a JavaScript function that toggles every checkboxes checked-state. I have a script that almost does this, but not quite..
function toggle(field) {
for (i = 0; i < field.length; i++) {
field[i].checked = !field[i].checked;
}
}
...and it is invoked like this (this is a separate checkbox that can be used to invert the selection)...
The JavaScript function works if I remove the brackets from the checkboxes' name, but then problems arise in the PHP-script that processes the form, because it relies on the fact that the ids are stored on an array.
How to toggle checboxes checked state with JavaScript when the checkboxes' names form an array? (or is there a better way to deal with this problem)
because brackets have special meaning in javascript, bracket can't be used in the object notation as part of the object's name. that is, you can't do doument.form.id[]. however, javascript allow another syntax commonly called the associative syntax. is very simple, you would include the string name of an object or property inside brackets. so, in your case you would do document.form['id[]']
my mom is javascript, dad is javascripter, granpa is javascriptor, and my little sister is javasRidiculous. my nature language is javascript, then come spanish and english -- me
Bookmarks