0

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
)

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

2 Comments

Well this part of the project is in the backend of the website, so there will be few people accessing that side of things, but will keep it in mind when using jquery in the future, thank you :)
Ah, that's fine then. I've got all kinds of backend bits which certainly don't degrade gracefully :) My preferred method of making sure things degrade gracefully is to think of the ideal interface, then work out how I can show all the necessary content using standard HTML, then add bells and whistles with jQuery.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.