Showing posts with label Get selected checkbox value using JQuery. Show all posts
Showing posts with label Get selected checkbox value using JQuery. Show all posts

Monday, 29 August 2016

Get selected checkbox value using JQuery

In this post, I will explain how to get all selected checkbox values in JQuery.

You can easily get all selected checkbox values in jQuery. By using each loop for all selected checkboxes and every time add selected checkbox value in a variable.

var chkId = '';
$(
'.chkNumber:checked').each(function() {
  chkId += $(
this).val() + ",";
});
chkId = chkId.slice(0,-1);
// Remove last comma

Select all CheckBox on single click
You can also check or uncheck all checkboxes with a single click. It is one line code, in the below example you check the SelectAll checkbox then all checkbox will check.
$('.chkNumber').prop('checked'true);

<!DOCTYPE html>
<html  lang="">
<head>
  <title>jQuery With Example</title>
  <script src="https://code.jquery.com/jquery-1.9.1.js" type="text/javascript"></script>
  <script type="text/javascript">
    $(function () {
      $('.btnGetAll').click(function () {
        if ($('.chkNumber:checked').length) {
          var chkId = '';
          $('.chkNumber:checked').each(function () {
            chkId += $(this).val() + ",";
          });
          chkId = chkId.slice(0, -1);
          alert(chkId);
        }
        else {
          alert('Nothing Selected');
        }
      });
      $('.chkSelectAll').click(function () {
        $('.chkNumber').prop('checked', $(this).is(':checked'));
      });
      $('.chkNumber').click(function () {
        if ($('.chkNumber:checked').length == $('.chkNumber').length) {
          $('.chkSelectAll').prop('checked', true);
        }
        else {
          $('.chkSelectAll').prop('checked', false);
        }
      });
    });
  </script>
</head>
<body>
  <div>
    <input type="checkbox" class="chkNumber" value="1" />One<br />
    <input type="checkbox" class="chkNumber" value="2" />Two<br />
    <input type="checkbox" class="chkNumber" value="3" />Three<br />
    <input type="checkbox" class="chkNumber" value="4" />Four<br />
    <input type="checkbox" class="chkNumber" value="5" />Five<br /><br />
  </div>
  <button type="button" class="btnGetAll">Get Selected Value</button><br>
  <input type="checkbox" class="chkSelectAll" />SelectAll
</body>
</html>