简体   繁体   中英

how to check if the listbox items are selected or not?

Hi I am developing one asp.net application. I have one listbox with certain values from database. In listbox i have items with checkbox and select all option. It is basically mutiselect listbox. I am able to display number of items selected in alert box. If i check select all i am able to display number of items using length property. Whenever i uncheck the select all option i want to display 0 because all the checkboxes will be unchecked. I tried in many ways still it is not working. This is my code. These are references.

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<link href="http://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.0.3/css/bootstrap.min.css"
    rel="stylesheet" type="text/css" />
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.0.3/js/bootstrap.min.js"></script>
<link href="http://cdn.rawgit.com/davidstutz/bootstrap-multiselect/master/dist/css/bootstrap-multiselect.css" rel="stylesheet" type="text/css" />
<script src="http://cdn.rawgit.com/davidstutz/bootstrap-multiselect/master/dist/js/bootstrap-multiselect.js" type="text/javascript"></script>

Below is my javascript code

$(function () {
          $('[id*=ddlvendors]').multiselect({
              includeSelectAllOption: true
          });
      });

This is my code to find the selected items from the listbox.

 $(".limitedNumbSelect2 option").each(function () {
                var val = $(this).val();
                var tempVal = $(".limitedNumbSelect2").val();

                if (tempVal.indexOf(val) >= 0 && selected.indexOf(val) < 0) {
                    selected.push(val);
                } else if (tempVal.indexOf(val) < 0 && selected.indexOf(val) >= 0) {
                    selected.splice(selected.indexOf(val), 1);
                }
            })
            alert(selected.length);

Whenever i uncheck select all my alert will not fire. May I have some suggestion on this? Thank you all.

My solution with vanilla JS would be to simple listen to the change-event and if the input has target.checked or not, trigger neccassary code: https://jsfiddle.net/67dnnhva/

var allCheckboxes = document.querySelectorAll(".allcheckboxes input");
var checkAllElement = document.querySelector("#chkall");

checkAllElement.addEventListener("change", toggleSelectAll);

function toggleSelectAll(input) {
    if (input.target.checked) {
    allCheckboxes.forEach(function(input) {
        input.checked = true;
    });
  } else {
    allCheckboxes.forEach(function(input) {
      input.checked = false;
    });
    alert("hello");
  }
}

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