krish
krish

Reputation: 167

select all in Multiselect dropdown

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

Answers (3)

user2575725
user2575725

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

KAD
KAD

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

guradio
guradio

Reputation: 15555

var selected=$('#filter-select option').prop('selected', true);
console.log(selected.text());
$('#filter-select').change(function(){
alert($('option:selected',this).text());

})

demo

When you select again the just get the new value

Upvotes: 0

Related Questions