How to "check" certain checkboxes only with jQuery?

I have an HTML form containing checkboxes on the form ..

<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 Uncheck All Flags

$('#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 functionality in which the user could have certain flags, depending on 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" />

therefore, if the user enters from 5 to 20 and clicks on the icon, he checks the checkboxes from 5-20.

Can you please help me imagine how this can be achieved. I can change the markup to apply some class identifiers / selecter, etc., if you suggest if this makes things easier. And I understand that this feature is for users who have javascript enabled browsers.

Thanks.

+3
3
$("#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);
});
+3

:

$('#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));
    });
});
+1

, index :

$('#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);
});
0

Source: https://habr.com/ru/post/1711817/


All Articles