Reputation: 53
I am making a html form which includes a multiple select box. What i want to do is to make a "select all" option in multiple select box so that if the user user click on that option all the options of select box will automatically gets selected if user deselect it all other option gets deselected. any ideas using jQuery?
<select MULTIPLE>
<option>Select All</option>
<option>value1</option>
<option>value2</option>
<option>value3</option>
<option>value4</option>
<option>value5</option>
<option>value6</option>
</select>
Upvotes: 3
Views: 11674
Reputation: 21499
I store status (selected/unselected) of options in data-selected
attribute on click event. Then use it to select/unselect all option of listbox.
$("select").on("click", function(){
if ($(this).find(":selected").text() == "Select All"){
if ($(this).attr("data-select") == "false")
$(this).attr("data-select", "true").find("option").prop("selected", true);
else
$(this).attr("data-select", "false").find("option").prop("selected", false);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select multiple data-select="false">>
<option>Select All</option>
<option>value1</option>
<option>value2</option>
<option>value3</option>
<option>value4</option>
<option>value5</option>
<option>value6</option>
</select>
Upvotes: 3
Reputation: 3928
You can do something like this using jQuery:
$('#selectAll').click(function() {
$('#persons option').prop('selected', true);
});
$('#unselectAll').click(function() {
$('#persons option').prop('selected', false);
});
input[type=button] {
width: 100px;
margin: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="button" id="selectAll" name="selectAll" value="Select All"><br />
<input type="button" id="unselectAll" name="unselectAll" value="Unselect All"><br /><br />
<select name="persons" id="persons" MULTIPLE size="8">
<option value="FR">Franck</option>
<option value="GE">Georges</option>
<option value="DA">David</option>
<option value="LU">Luc</option>
<option value="DO">Donald</option>
<option value="FR">FRANCOIS</option>
</select>
Upvotes: 1