Valhalla Legends Forums Archive | Web Development | Javascript, SELECT value array

AuthorMessageTime
Grok
When a SELECT is not "multiselect", getting its value attribute (the item selected) is easy.  Clicking on a name entry in this example will show the associated value.

[code]<script language="javascript">
  function ShowSelectedGroups() {
    var svals = document.form1.groups.value;
    alert('Groups='+svals);
  }
</script>
<form name="form1">
  <select name="groups" onchange="ShowSelectedGroups();">
    <option value="1">Grok</option>
    <option value="2">Raven</option>
    <option value="3">Wizzbert</option>
  </select>
</form>[/code]

But when the SELECT is a multiselect, the value shown is always the top entry.  Thus if you select all 3 entries, it will say "Groups=1".  How do I get it to say "Groups=1,2,3"?

The real question is if select.value returns multiple values, how do I know this, and combine them for display?
January 26, 2005, 7:48 PM
Grok
Also tried this -- which still shows only the first selected value:
[code]      function ShowSelectedGroups() {
        var savals = new Array(document.form1.groups.value);
        var svals = savals.toString();
        alert('Groups='+svals);
      }
[/code]
January 26, 2005, 8:08 PM
TehUser
[code]
var selectedArray = new Array();
var selectionObject = document.getElementById('groups');
var index = 0;
var i;

for( i = 0; i < selectionObject.options.length; i++ )
{
  if( selectionObject.options[i].selected )
    selectedArray[index++] = selectionObject.options[i].value;
}
[/code]

Should work or at least give you the idea.
January 26, 2005, 10:56 PM
Grok
No, I do not want to loop through all the options to see what is selected.  I have been told that the value property of the select object contains the values that are selected.  Where it is only one, it contains that value, and when it is more than one, it is presented either as a comma-delimited list of values, or an array, or something.  So I guess the best question is how do I determine the datatype of the document.form1.groups.value object?  isArray() does not appear to work for me.
January 26, 2005, 11:24 PM
TehUser
typeof() will tell you the type.

The form.select.value is always the value of one selection item.  It does not return an array.
January 27, 2005, 12:20 AM
Grok
Is it true that .value is only one item, even when >1 are selected in a multiselect?  If you found the official spec on this, share, I could not locate it on any javascript/DOM sites.
January 28, 2005, 3:25 PM
TehUser
[img]http://www.freewebs.com/tehuser/javascript.png[/img]
January 28, 2005, 5:21 PM
peofeoknight
grok what are you trying to do (big picture)?
January 29, 2005, 1:22 AM
UnLeaDeD
Try making another variable that stores the option value numbers. Then use if statements (depending on what your doing) to display objects.
February 6, 2005, 4:47 AM

Search