Check control

jQuery-check control by specified range

by I Sang Hyeon

HTML

<h2>Checkbox Control with specified length</h2>
<table>
  <thead>
    <tr>
      <th>
        <input type="checkbox" id="controlCheckbox">
      </th>
      <th>Order Number</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td><input type="checkbox" class="chk"></td>
      <td>1</td>
    </tr>
    <tr>
      <td><input type="checkbox" class="chk"></td>
      <td>2</td>
    </tr>
    <tr>
      <td><input type="checkbox" class="chk"></td>
      <td>3</td>
    </tr>
    <tr>
      <td><input type="checkbox" class="chk"></td>
      <td>4</td>
    </tr>
    <tr>
      <td><input type="checkbox" class="chk"></td>
      <td>5</td>
    </tr>
    <tr>
      <td><input type="checkbox" class="chk"></td>
      <td>6</td>
    </tr>
    <tr>
      <td><input type="checkbox" class="chk"></td>
      <td>7</td>
    </tr>
    <tr>
      <td><input type="checkbox" class="chk"></td>
      <td>8</td>
    </tr>
    <tr>
      <td><input type="checkbox" class="chk"></td>
      <td>9</td>
    </tr>
    <tr>
      <td><input type="checkbox" class="chk"></td>
      <td>10</td>
    </tr>
  </tbody>
  <tfooter>
    <tr>
      <td colspan="2">
        <p>
        * From: <input type="text" id="txtNoFrom" class="txtInputNo"> ~
        To: <input type="text" id="txtNoTo" class="txtInputNo"> 
        <span>
          <input type="button" id="cmdDo" class="cmdSpecifyControl" value="Do Check">
          <input type="button" id="cmdUndo" class="cmdSpecifyControl" value="Undo Check">
        </span>
        </p>
      </td>
    </tr>
  </tfooter>
</table>

CSS

table {
    border-collapse: collapse;
}

table, th, td {
    border: 1px solid black;
}

th {
  background-color: #AAAAAA;
}

td {
    text-align: center;
    vertical-align: middle;
}

JavaScript

/* Checkbox Control with specified range */
var noFrom = 0;
var noTo = 0;
var doCheck = true;

$(document).ready(function(){

	$('#controlCheckbox').click(function(){
    $('.chk').prop('checked', $(this).is(":checked"));
  });
  
  $('.chk').click(function(){
  	validateParentCheckbox();
  });
  
  $('.cmdSpecifyControl').click(function(){
  	//alert($(this).prop('id'));
    noFrom 	= $('#txtNoFrom').val();
    noTo		= $('#txtNoTo').val();
    doCheck	= $(this).prop('id') === 'cmdDo' ? true : false;
    //alert('noFrom: '+noFrom+'\n noTo: '+noTo+'\n doCheck: '+doCheck);
    
    if($.isNumeric(noFrom) && $.isNumeric(noTo) && noFrom <= noTo){
    	$('.chk').each(function(index){
      	if(index+1 >= noFrom && index+1 <= noTo){
        	$(this).prop('checked',doCheck);
        }
      });
    } else {
    	alert('Only allowed Number \n and From value should less then To value');
    }
    validateParentCheckbox();
  });
});

function validateParentCheckbox(){
	var isAllChecked = true;
	$('.chk').each(function(){
    	if(! $(this).is(":checked")){
      	isAllChecked = false;
      }
    });
  $('#controlCheckbox').prop('checked',isAllChecked);
}