March 29, 2012

JQuery select all options of multi-select select box on click

Question by Sachyn

This is my HTML

<select name="countries" id="countries" MULTIPLE size="8">
   <option value="UK">UK</option>
   <option value="US">US</option>
   <option value="Canada">Canada</option>
   <option value="France">France</option>
   <option value="India">India</option>
   <option value="China">China</option>
</select>
<br />
<input type="button" id="select_all" name="select_all" value="Select All">

When user click on ‘Select All’ button, I want all the options in the select box to be selected

$('#select_all').click( function() {
    // ?
});

Answer by Darin Dimitrov

Try this:

$('#select_all').click(function() {
    $('#countries option').attr('selected', 'selected');
});

And here’s a live demo.

Answer by Starx

Give selected attribute to all options like this

$('#countries option').attr('selected', 'selected');

Usage:

$('#select_all').click( function() {
    $('#countries option').attr('selected', 'selected');
});

Update

In case you are using 1.6+, better option would be to use .prop() instead of .attr()

$('#select_all').click( function() {
    $('#countries option').prop('selected', true);
});

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!