www.webdeveloper.com
Results 1 to 3 of 3

Thread: JavaScript checkbox toggling..

  1. #1
    Join Date
    Apr 2009
    Posts
    3

    resolved JavaScript checkbox toggling..

    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)...

    <input type="checkbox" onClick="toggle(document.form.id);" />

    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)

  2. #2
    Join Date
    May 2006
    Location
    Odenton, MD
    Posts
    1,449
    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

  3. #3
    Join Date
    Apr 2009
    Posts
    3
    Ah, It works now perfectly.

    Thanks

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles