Pranav Unde Pranav Unde -4 years ago 62
jQuery Question

Unchecked in between checkbox using shift key like gmail

Using following code I try to implement gmail like shift key functionality.



var lastChecked = null;

$(document).ready(function() {
var $chkboxes = $('.chkbox');
$chkboxes.click(function(e) {
if (!lastChecked) {
lastChecked = this;
return;
}

if (e.shiftKey) {
var start = $chkboxes.index(this);
var end = $chkboxes.index(lastChecked);

$chkboxes.slice(Math.min(start, end), Math.max(start, end) + 1).prop('checked', lastChecked.checked);

}

lastChecked = this;
});
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" id="id_chk1" class="chkbox" value="1" />Check 1<br/>
<input type="checkbox" id="id_chk2" class="chkbox" value="2" />Check 2<br/>
<input type="checkbox" id="id_chk3" class="chkbox" value="3" />Check 3<br/>
<input type="checkbox" id="id_chk4" class="chkbox" value="4" />Check 4<br/>
<input type="checkbox" id="id_chk5" class="chkbox" value="5" />Check 5<br/>





But the problem is that if I select all the checkboxes and using shift key if I unchecked 3rd checkbox then its not unchecked 4th & 5th. This is working for gmail. Any alternative to this?

Answer Source

Use this.checked instead of lastChecked.checked when setting the checked property. So if you're unchecking a box with the shift key, it will uncheck all the other boxes, rather than copying the checked property of the previous checkbox.

var lastChecked = null;

$(document).ready(function() {
  var $chkboxes = $('.chkbox');
  $chkboxes.click(function(e) {
    if (!lastChecked) {
      lastChecked = this;
      return;
    }

    if (e.shiftKey) {
      var start = $chkboxes.index(this);
      var end = $chkboxes.index(lastChecked);

      $chkboxes.slice(Math.min(start, end), Math.max(start, end) + 1).prop('checked', this.checked);

    }

    lastChecked = this;
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" id="id_chk1" class="chkbox" value="1" />Check 1<br/>
<input type="checkbox" id="id_chk2" class="chkbox" value="2" />Check 2<br/>
<input type="checkbox" id="id_chk3" class="chkbox" value="3" />Check 3<br/>
<input type="checkbox" id="id_chk4" class="chkbox" value="4" />Check 4<br/>
<input type="checkbox" id="id_chk5" class="chkbox" value="5" />Check 5<br/>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download