views:

580

answers:

3

Hi

I have a HTML form containing checkboxes in the form of ..

<input type="checkbox" name="range[]" class="range_opts" id="range-1" value="1" /> 1 <br />
<input type="checkbox" name="range[]" class="range_opts" id="range-2" value="2" /> 2 <br />
<input type="checkbox" name="range[]" class="range_opts" id="range-3" value="3" /> 3 <br />
     ...
     ...
<input type="checkbox" name="range[]" class="range_opts" id="range-28" value="28" /> 28<br />
<input type="checkbox" name="range[]" class="range_opts" id="range-29" value="29" /> 29<br />
<input type="checkbox" name="range[]" class="range_opts" id="range-30" value="30" /> 30<br />

With this JS Code I Select all or Deselect all checkboxes

$('#select_all_ranges').click(function() {
 $('input[name="range[]"]').each(function() {
  this.checked = true;
 });
});
$('#deselect_all_ranges').click(function() {
 $('input[name="range[]"]').each(function() {
  this.checked = false;
 });
});

But I need the functionality where user would be able to have certain checkboxes selected, depending upon the input

    <input type="text" name="from_range" id="frm_range" />
   <input type="text" name="to_range" id="to_range" />
    <img src="icon.png" id="range123" />

so if user inputs from 5 to 20 and clicks on icon it checks checkboxes from 5-20.

Can you please help me some ideas how this can be achieved. I can alter markup to apply some classes/selecter ids etc if you suggest, if it would make it any easier. And I understand that this functionality is for users having javascript enabled browsers.

Thanks.

+1  A: 

How about:

$('#range123').click(function() {
    var bottom = $("#frm_range").value;
    var top = $("#to_range").value;
    $('input[name="range[]"]').each(function() {
            this.checked = ((this.value > bottom) && (this.value < top));
    });
});
Stobor
Yep, I had just finshed writing nearly same. Thanks Anyway.
Wbdvlpr
+2  A: 
$("#range123").click(function() {
  var from = $("#frm_range").val();
  var to = $("#to_range").val();
  var expr = ":checkbox.range_opts:lt(" + to + ")";
  if (from > 1) {
    expr += ":gt(" + (from-1) + ")";
  }
  $(expr).attr("checked", true);
});
cletus
@cletus .. can you please help me know how do these gt and lt work? I mean do they compare agains "element id" value? Thanks
Wbdvlpr
http://docs.jquery.com/Selectors/gt#index :gt() and :lt() work on the index into the set and start at 0. Say $("blah") returns 10 items. $("blah:gt(7)") will return the 9th and 10th item (7 on 0 index is the 8th item).
cletus
ah I see. Cool. Thanks for you help.
Wbdvlpr
A: 

Yes, you can simply check the index while selecting the checkboxes:

$('#select_all_ranges').click(function() {
    var from = $('#frm_range').val();
    var to = $('#to_range').val();
    var expr = '.range_opts:gt(' + (from-2) + '):lt(' + (to-1) + ')';
    $(expr).attr("checked", true);
});
Tim Büthe