0

I'm trying to add the option of selecting multiple checkboxes at the same time in an apex tabular form:

I originally wanted to write some Javascript allowing to select a range of checkboxes using the intutive "standard" way of spreadsheet software to:

  1. select first item
  2. press & hold shift
  3. select last item

But for the sake of easier implementation, I decided to just use an apex button (setting a REQUEST). My code should select all checkboxes from the first selected to the last selected. But it simply doesn't and I can't see why.

var $firstChecked = $('input[type=checkbox]:checked').first();
var $lastChecked = $('input[type=checkbox]:checked').last();
$firstChecked.nextUntil($lastChecked, 'input[type=checkbox]').each(function () {
    $(this).prop('checked', true);
});

I'm almost sure that I am doing something wrong with nextUntil because

$('input[type=checkbox]:checked').prop('checked', false);

works just fine.

[JSFiddle] (using the copied html code from apex)

  • What is wrong with my javascript code?
  • Is it possible to code the "intuitive way" with jQuery (logging the shift key)?
cdMinix
  • 655
  • 1
  • 7
  • 29

3 Answers3

1

try this :-

$("#myButton").click(function () {
 var f=$("input[type=checkbox]").index($('input[type=checkbox]:checked').first());    
 var ls = $("input[type=checkbox]").index($('input[type=checkbox]:checked').last());
   for(var i=f;i<=ls;i++)
     {
       $("input[type=checkbox]").eq(i).prop('checked', true);
     }   
  });

  $("#myOtherButton").click(function () {
   $('input[type=checkbox]:checked').prop('checked', false);
  });

Demo

Umesh Sehta
  • 10,555
  • 5
  • 39
  • 68
1

You are trying to get next checkbox until last checked checkbox. But as per HTML DOM structure, all checkboxes are not siblings hence cannot use .nextUntil(). But they are present in each sibling trs, so find first and last trs and check the checkboxes inside tr between them.

Try this :

$("#myButton").click(function () {
    var $firstChecked = $('input[type=checkbox]:checked:first').closest('tr');
    var $lastChecked = $('input[type=checkbox]:checked:last').closest('tr');
    $firstChecked.nextUntil($lastChecked).find('input[type=checkbox]').prop('checked', true);
});

Demo

Bhushan Kawadkar
  • 28,279
  • 5
  • 35
  • 57
1

Try the following using tr parent of checkbox,

var start = $firstChecked.parents('tr');
var last = $lastChecked.parents('tr');

$(start).nextUntil(last).each(function(){
    $(':checkbox',this).prop('checked',true);
});

Demo

Shaunak D
  • 20,588
  • 10
  • 46
  • 79