简体   繁体   中英

How to get multiselect checkbox value in jquery

I have a multiselect drop-down with checkbox( jquery includeSelectAllOption ), i want last selected value only instead of all checked checkbox value.

<select class="form-control" id="change_city" multiple="multiple">
  <?php foreach ($city_array as $key => $value) {
     # code...
      echo "<option value=".$value['city_id'].">".$value['city_name']."</option>";
  } ?>
</select>

<script>
    $(function() {
        $('#change_city').multiselect({
            includeSelectAllOption: true
        });
    });

</script>

Well, then simply just make it an extra option and remove includeSelectAllOption . When user clicks on "select all", deselect all other options and keep "select all".

 var handler = function(){ let val = $(this).val(); if(val === null) return; val.forEach(function(value){ if(value == "all"){ $("#change_city option:selected").prop("selected", false); $('#change_city option[value="all"]').prop('selected', true); } }); } $("#change_city").on("change", handler); 
 #change_city { height: 150px; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <select class="form-control" id="change_city" multiple="multiple"> <option value="1">City 1</option>"; <option value="2">City 2</option>"; <option value="3">City 3</option>"; <option value="4">City 4</option>"; <option value="all">Select All</option>"; </select> 

see below code i hope may help you

<label>Country:</label>
    <select class="country" multiple="multiple" size="5">
        <option>United States</option>
        <option>India</option>
        <option>United Kingdom</option>
        <option>Brazil</option>
        <option>Germany</option>
    </select>
    <button type="button">Get Values</button>



<script type="text/javascript">
$(document).ready(function() {
$("button").click(function(){
    var countries = [];
    $.each($(".country option:selected"), function(){            
        countries.push($(this).val());
    });
    //countries.join(", ")
    alert("You have selected the country - " + countries.slice(-1)[0]);
});
});
</script >

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM