Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
  1. #1
    New Coder
    Join Date
    Jun 2002
    Posts
    12
    Thanks
    0
    Thanked 0 Times in 0 Posts

    validating checkbox arrays

    I am trying to use both PHP and Javascript and am running into a small conflict. I have a page with many check boxes, and usually, only 2 or 3 out of about 60 dynamically created checkboxes are checked on each page.

    To make things easier with PHP and MySQL, I have the checkbox created with the name as an array. (PHP seems to require the [] after the name to see it as an array.)

    <input type="checkbox" name="form_requested[]" value="$form_id"> $form_name<br>

    The PHP will allow me to easily pull up the boxes that are checked as an array and I can use a foreach loop to look at only the items that are checked. It also allows me to easily create more forms without having to change the program.

    My problem is that when I try to validate the form to make sure that at least one box is checked, JavaScript does not seem to like the fact that the checkbox is an array. If I try to use

    for (index = 0; document.form.form_requested[].length; index ++) {
    if (document.form.form_requested[][index] == true) {
    count +=1;
    }
    }
    // check here if count >0

    I get a syntax error. If I use

    for (index = 0; document.form.form_requested.length; index ++) {
    if (document.form.form_requested[index] == true) {
    count +=1;
    }
    }
    //check here if count > 0

    the script does not work because the names are different.

    Is there a way to validate the checboxes without loosing the array? Or do I need to abandon the array concept and find a different way to dynamically create the boxes in order to validate the form?

    Thanx for any info you can give.

    JustLearning
    ~~~ Pretend that I have a long and creative signature. ~~~

  • #2
    Regular Coder
    Join Date
    Jul 2002
    Location
    Western US
    Posts
    169
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Reference them through elements[]

    for (index = 0; document.form.elements['form_requested[]'].length; index ++) {
    if (document.form.elements['form_requested[]'].index] == true) {
    count +=1;
    }
    }

    This allows for special characters in a variable name like a ., that useful in JSP.

    ShriekForth


  •  

    Posting Permissions

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