user785533
user785533

Reputation:

HTML Multi Select Box, Select multiple items using jQuery

I have a problem with the multi-select box. I tried to select multiple values using jQuery, but only the last one is selected, can anyone help me please? Here is my code:

<script>
$(function(){
 <?php 
 foreach ($selectdefaults as $s):
   ?>   
   $('#q<?php echo $s['campsetjoin']['campid'];?> select').val('<?php echo $s['campsetjoin']['setid'];?>');
   <?php  
 endforeach;
 ?> 
});
</script>

Here is my HTML source (this is generated with PHP):

<table>
<tr>
    <td>
        <form id="s1" name="camps">
            <input type="hidden" name="camid" value="1" />
            <strong> Camp 1 </strong>
        </form>
    </td>
    <td align="right" id="q1">
        <select name="qsets" multiple="multiple">
            <option value="1">common set</option>
            <option value="2">test set</option>
        </select>
    </td>
    <td>
        <input type="button" value="update" cid="1" class="btncdsave" />
    </td>
</tr>
<tr>
    <td>
        <form id="s9" name="camps">
            <input type="hidden" name="camid" value="9" />
            <strong> Camp 2 </strong>
        </form>
    </td>
    <td align="right" id="q9">
        <select name="qsets" multiple="multiple">
            <option value="1">common set</option>
            <option value="2">test set</option>
        </select>
    </td>
    <td>
        <input type="button" value="update" cid="9" class="btncdsave" />
    </td>
</tr>
<tr>
    <td>
        <form id="s10" name="camps">
            <input type="hidden" name="camid" value="10" />
            <strong> Camp 3 </strong>
        </form>
    </td>
    <td align="right" id="q10">
        <select name="qsets" multiple="multiple">
            <option value="1">common set</option>
            <option value="2">test set</option>
        </select>
    </td>
    <td>
        <input type="button" value="update" cid="10" class="btncdsave" />
    </td>
</tr>
</table>

So I need to select multiple values of the select box. I can get the form id and select box value ids for selection. Thanks for you help.

Upvotes: 1

Views: 1999

Answers (1)

Nicola Peluchetti
Nicola Peluchetti

Reputation: 76870

If you want to select multiple values, pass an array with those values

 $('#q10 select').val(['1', '2']);

fiddle here http://jsfiddle.net/p8R4k/

Upvotes: 1

Related Questions