wilmens™

by William W. Mensah

HTML form, 1 element array vs javascript

  • Friday Oct 30,2009 10:45 AM
  • By wmensah
  • In Thoughts

For some reason, when you create an array inside a HTML form and pass it to a javascript function, the 1st element in the array turns out to be undefined when it is the only element in the array.

This can occur, for example, in the case where you have a group of checkboxes and want to pass an array of them to a javascript function to, lets say, check/uncheck all of them. If there is only one checkbox, don’t blow your brains out wondering why it’s not working. Do an alert inside the javascript function and try to print out the value of the first element. You’ll find out that it’s undefined.

I’ve Googled/Binged (can we make that a term now?) around and haven’t found any legit solution, so my suggestion is to use a hidden checkbox field and assign it a value (that will be stored in the array) that would never be used when being processed by your javascript function – like a negative number if your array is storing only positive numbers.

That should save you some headache. If there’s a better solution/workaround, please comment on this.

, , , , ,



Leave a reply