views:

2739

answers:

4

I have a form with a select box that allows multiple options. After a user saves these options, it stores them in a database table.

I can then read this database table to get the options they chose one again. I need to be able to grab this data from the database, put it into an array, then have the options in that select box to be pre-selected when they go to "Edit" their options.

Reading the data into an array is fine, and I know how to make a single option selected within a select box, however I'm not sure how to handle multiple options being selected in javascript.

Can someone help me figure out the javascript required to do this?

+2  A: 

Declare it to be "Multiple"

<select name="options" MULTIPLE>

Further Reading...

As for the selecting, I would handle that server-side:

PHP Example:

$options = array("red","blue","orange","green");
$chosen  = array("blue","green");

<select name="favColors" MULTIPLE size="4">
<?php foreach ($options as $color) { ?>
<option <?php print (in_array($color,$chosen)) ? "selected" : "" ; ?>>
  <?php print $color; ?>
</option>
<?php } ?>
</select>

Which outputs:

<select name="favColors" MULTIPLE size="4">
  <option>Red</option>
  <option selected>Blue</option>
  <option>Orange</option>
  <option selected>Green</option>
</select>

Selecting with jQuery

You can also do the selection with jQuery (not suggested, but you requested it explicitly), but you'll need to transfer the selected elements names into a javascript array.

var chosen = ['blue','green']; // this will have to be made server-side

$("select.someClass option").each(function(){
  if (in_array($(this).val(), chosen)) {
    $(this).attr("selected","selected");
  }
});

function in_array (needle, haystack, argStrict) {
    var key = '', strict = !!argStrict;
    if (strict) {
        for (key in haystack) {
            if (haystack[key] === needle) {
                return true;
            }
        }
    } else {
        for (key in haystack) {
            if (haystack[key] == needle) {
                return true;
            }
        }
    }
    return false;
}
Jonathan Sampson
I already have the select form, I was looking more for a javascript solution to the auto select. Every other part of the form uses javascript, I'm just not sure how to select multiple options with the javascript code.
Dave Hunt
Doing it server-side makes more sense, and you will still end up generating an array server-side for the client-side code.
Residuum
Server side does make more sense, but I don't want to redo everything thats already done. The previous developer used all javascript, so I'm just going to stick with it for this.
Dave Hunt
+2  A: 

A pure javascript solution

<select id="choice" multiple="multiple">
  <option value="1">One</option>
  <option value="2">two</option>
  <option value="3">three</option>
</select>
<script type="text/javascript">

var optionsToSelect = ['One', 'three'];
var select = document.getElementById( 'choice' );

for ( var i = 0, l = select.options.length, o; i < l; i++ )
{
  o = select.options[i];
  if ( optionsToSelect.indexOf( o.text ) != -1 )
  {
    o.selected = true;
  }
}

</script>

Although I agree this should be done server-side.

Peter Bailey
This is close, however the values stored are not the "index" of the options, they are the values of the options.
Dave Hunt
Simple fix - answer updated!
Peter Bailey
A: 

You can get access to the options array of a selected object by going document.getElementById("cars").options where 'cars' is the select object.

Once you have that you can call option[i].setAttribute('selected', 'selected'); to select an option.

I agree with every one else that you are better off doing this server side though.

kertap
A: 
<script language="JavaScript" type="text/javascript">
<!--
function loopSelected()
{
  var txtSelectedValuesObj = document.getElementById('txtSelectedValues');
  var selectedArray = new Array();
  var selObj = document.getElementById('selSeaShells');
  var i;
  var count = 0;
  for (i=0; i<selObj.options.length; i++) {
    if (selObj.options[i].selected) {
      selectedArray[count] = selObj.options[i].value;
      count++;
    }
  }
  txtSelectedValuesObj.value = selectedArray;
}
function openInNewWindow(frm)
{
  // open a blank window
  var aWindow = window.open('', 'Tutorial004NewWindow',
   'scrollbars=yes,menubar=yes,resizable=yes,toolbar=no,width=400,height=400');

  // set the target to the blank window
  frm.target = 'Tutorial004NewWindow';

  // submit
  frm.submit();
}
//-->
</script>
The HTML
<form action="tutorial004_nw.html" method="get">
  <table border="1" cellpadding="10" cellspacing="0">
  <tr>
    <td valign="top">
      <input type="button" value="Submit" onclick="openInNewWindow(this.form);" />
      <input type="button" value="Loop Selected" onclick="loopSelected();" />
      <br />
      <select name="selSea" id="selSeaShells" size="5" multiple="multiple">
        <option value="val0" selected>sea zero</option>
        <option value="val1">sea one</option>
        <option value="val2">sea two</option>
        <option value="val3">sea three</option>
        <option value="val4">sea four</option>
      </select>
    </td>
    <td valign="top">
      <input type="text" id="txtSelectedValues" />
      selected array
    </td>
  </tr>
  </table>
</form>
Avinash