js errors when referring to <select multiple> names

JavaScript and client side scripting.

Moderator: General Moderators

Post Reply
dickey
Forum Commoner
Posts: 50
Joined: Thu May 16, 2002 8:04 pm
Location: Sydney, Australia

js errors when referring to <select multiple> names

Post by dickey »

feyd | Please use

Code: Select all

,

Code: Select all

and [syntax="..."] tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read:  [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url] to learn how to do it too.[/color]


Imagine I have:
[syntax="html"]
<select multiple name="members[]">
  <option value="1001">Tom</option>
  <option value="1002">Dick</option>
  <option value="1003">Harry</option>
</select>

If I write a js function that refers to this select how do I refer to it with the square brackets.

If I name it just members the js works, but when posted to a PHP page I cannot obtain the multiple values unless the select name can be interpreted as an array (hence the square brackets).

For example: a function that selects all options triggered by some event works as

Code: Select all

function allSelect()
{
List = document.form.members;

  for (i=0; i<List.length; i++)
  {
  List.options[i].selected = true;
  }
}
, but fails when refered to as List = document.form.members[]; probably as it interprets the [] as an array.

I require both the js and to name the <select> for use in php.

Any assistance would be appreciated.

- Andrew


feyd | Please use [php],[/syntax]

Code: Select all

and [syntax="..."] tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read:  [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url] to learn how to do it too.[/color]
User avatar
Chris Corbyn
Breakbeat Nuttzer
Posts: 13098
Joined: Wed Mar 24, 2004 7:57 am
Location: Melbourne, Australia

Post by Chris Corbyn »

Don't. Use DOM, with document.getElementById() ;)

Code: Select all

<select multiple id="members" name="members[]">
  <option value="1001">Tom</option>
  <option value="1002">Dick</option>
  <option value="1003">Harry</option>
</select>

Code: Select all

function allSelect()
{
List = document.getElementById('members');

  for (i=0; i<List.length; i++)
  {
  List.options[i].selected = true;
  }
}
Post Reply