Reputation: 167
Hi I have a dropdown with checkbox. The dropdown list will be something like this: * Select All * N1 * N2 * N3 * N4 I want to select all the checkboxes by default. But when the user wants to select selectively, he/she has to uncheck select all which will unselect all the checkboxes and then he/she can select.
<select id="filter-select" multiple="multiple" >
<option value="1">Select All</option>
<option value="2">N1</option>
<option value="3">N2</option>
<option value="4">N3</option>
<option value="5">N4</option>
<option value="6">N5</option>
<option value="7">N6</option>
</select>
How to do this using Javascript/JQuery?
Upvotes: 1
Views: 14532
Reputation:
Try using change
handler with selectedIndex
$(function() {
var filter = $('#filter-select');
filter.on('change', function() {
if (this.selectedIndex) return; //not `Select All`
filter.find('option:gt(0)').prop('selected', true);
filter.find('option').eq(0).prop('selected', false);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<select id="filter-select" multiple="multiple">
<option value="1">Select All</option>
<option value="2">N1</option>
<option value="3">N2</option>
<option value="4">N3</option>
<option value="5">N4</option>
<option value="6">N5</option>
<option value="7">N6</option>
</select>
Upvotes: 4
Reputation: 11102
Use prop
to set the selected to true and in the selector you need to select all the options inside #filter-select
:
Update :
Updated the snippet to check if the selected value is option 1 in select (i.e SelectAll) on select change event, if so then select all options and clear the selection of the first option.
selectAll();
$('#filter-select').change(function(){
if($("#filter-select option[value='1']").is(':selected'))
{
selectAll();
}
})
function selectAll()
{
$('#filter-select option').prop('selected', true);
$("#filter-select option[value='1']").prop('selected', false);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="filter-select" multiple="multiple" >
<option value="1">Select All</option>
<option value="2">N1</option>
<option value="3">N2</option>
<option value="4">N3</option>
<option value="5">N4</option>
<option value="6">N5</option>
<option value="7">N6</option>
</select>
Upvotes: 1