Page 1 of 1

checking multiple-select boxes client-side with Javascript?

Posted: Wed May 28, 2003 4:57 pm
by patrikG
To handle data from a multiple-select form the php manuals advises to use a name to identify multiple-select boxes that has [] at the end
(e.g. <SELECT name="status_list[]" multiple size="8">).

PHP has no problem with handling this - but Javascript does. Square brackets [] are not allowed because Javascript thinks it is an array and naturally produces and error when parsing something like this:

document.form.status_list[].options.add(newElem2);

Anyone have a solution handy?

Much appreciated!

id

Posted: Wed May 28, 2003 7:14 pm
by phpScott
yes the dom doen't like the [] after a name.
The solution I use is to give everything an id and then use the id to access it.

Code: Select all

<select name="selectMe&#1111;]" id="selectMe">
<option value=1>select 1</option>
<option value=2>select 2</option>
<option value=3>select 3</option>
<option value=4>select 4</option>
</select>
then in your javascript

Code: Select all

selectValue=document.getElementById('selectMe').value;
alert(selectValue);
That should get you started. I can't remeber how js handles multi selects but you get the idea.

I found this trick when using creating dynamic amounts of checkboxes and had to test to see if more then 10 where checked.

phpScott

Posted: Wed May 28, 2003 7:51 pm
by patrikG
Excellent idead! It works! Thanks a lot! :D

Posted: Sat Jun 03, 2006 7:58 pm
by Jet Black
I'm having similar problems.

I'm using an overlaoded checkbox group:

Code: Select all

<INPUT id='grade_3_classes_id' TYPE=CHECKBOX NAME='grade_3_classes_id[]' VALUE=1>
                    <INPUT id='grade_3_classes_id' TYPE=CHECKBOX NAME='grade_3_classes_id[]' VALUE=9>
However, using document.getElementById doesn't work, as per the definition of the HTML id tag, the id must be unique, I.E. cannot be overloaded like the name. I'm at a loss as to how I can have a multi select check box that's compatible with php and javascript at the same time.

Javascript code:

Code: Select all

cbxGroup=document.getElementById('grade_3_classes_id');
        for(j=0;j<cbxGroup.length;j++)
            cbxGroup[j].checked=true;

Posted: Sun Jun 04, 2006 6:28 am
by Chris Corbyn
Why don't you append the value to the id to make them all unique? :)