www.webdeveloper.com
Results 1 to 3 of 3

Thread: Finding length of a Checkbox set with only 1 checkbox

  1. #1
    Join Date
    Oct 2007
    Posts
    16

    Exclamation Finding length of a Checkbox set with only 1 checkbox

    I've got several functions that require sending the values of all the checked boxes on a form to a PHP page. The scripts all work as long as there are at least 2 checkboxes. If there is only 1 checkbox present document.form.checkboxList.length is returned as undefined. I'm not sure why it's being returned as undefined, it is in reality 1. This isn't a 0-based count system (the length)

    currently I've got...

    Code:
    for (i=0; i < theForm.servee.length; i++) {
    if(theForm.servee[i].checked == true) {
    serviceID[i] = theForm.servee[i].value
    }
    }
    Any ideas as to why the length of 1 checkbox is undefined?

  2. #2
    Join Date
    Mar 2007
    Location
    U.K.
    Posts
    1,127
    Quote Originally Posted by bdmovies View Post
    Any ideas as to why the length of 1 checkbox is undefined?
    Because a single element doesn't form an array. Also your loop is potentially skipping array elements. You can do it like this:
    Code:
    if(theForm.servee.length)
    {
     for (var i=0, j=0; i < theForm.servee.length; i++) 
      if(theForm.servee[ i ].checked == true) 
       serviceID[ j++ ] = theForm.servee[ i ].value;
    }
    else
     if(theForm.servee.checked) 
      serviceID[0] = theForm.servee.value;
    or you could use Array.push.

  3. #3
    Join Date
    Mar 2005
    Location
    Sydney, Australia
    Posts
    7,974
    A simple solution is to always include a hidden field that will be part of the same array due to its having the same name. You then know that the true count is one less than the length of the array and you ignore the first or last entry in the array (depending on where you put the hidden field).

Thread Information

Users Browsing this Thread

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

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