Question

I'm trying to produce a multiple select list with selected options based from a php array, in jquery. I can't seem to get it working, this is my code:

My select list:

<select name="modules[]" id="modules" class="inputbox" size="10" multiple="multiple">
  <option value="1">Module 01</option>
  <option value="2">Module 02</option>
  <option value="3">Module 03</option>
</select>

My PHP/JQuery (attempt):

<script type="text/javascript" language="javascript">
<?php 
$modules = explode(';',$row->modules);
if (is_array($modules)) {
    foreach($modules as $moduleID) { 
    ?>
    jQuery("#modules").val("<?php echo $moduleID; ?>");
    <?php 
    };
} else { 
?>
jQuery("#modules").val("<?php echo $row->modules; ?>");
<?php 
};
?>
</script>

Which looks like (plain jquery):

<script type="text/javascript" language="javascript">
  jQuery("#modules").val("3");
  jQuery("#modules").val("1");
</script>

And this is my php array (after being exploded):

Array
(
    [0] => 3
    [1] => 1
)
Was it helpful?

Solution

You need to pass an array to val():

<script type="text/javascript">
  jQuery("#modules").val(["3","1"]);
</script>

From the jQuery docs:

This method is typically used to set the values of form fields. For <select multiple="multiple"> elements, multiple <option>s can be selected by passing in an array.

OTHER TIPS

Do you have some kind of alternative for users who have Javascript disabled? It's not always appropriate, and the number of users this will affect is ever-decreasing (mobile phone users are probably the biggest proportion nowadays) but IMO its still worth the effort.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top