jquery / php select multiple selected options from php array in jquery

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
)

Answers


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.


Need Your Help

How to resolve suexec policy violation causing error 500 using git-http-backend?

git suexec

I'm trying to get git-http-backend working on my remote vps with no luck. I've adjusted httpd.conf in a way similar to the on this question, but as soon as I add the ScriptAlias directive, the error

Repeat scheduled tasks on selected days in Android sdk alarm manager

android sdk calendar alarmmanager

I have tried to do this without bothering the experts and have read numerous threads here and on other sites. It is clearly my brain not understanding what needs to be done in order for this to wor...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.