thilina.gg thilina.gg - 1 year ago 98
Javascript Question

JQuery Checkbox validation one

I have following html and jquery code segments to validate at least one check box. I am new for jQuery so I can not validate this two check boxes. Please help me. Thank you

<div class="row">
<div class="form-horizontal">
<label class="col-sm-5 control-label input-sm">Payement Type</label>
<div class="col-sm-5">
<span id="errfnBC9" style="color:red;font-size:8pt"></span>
<input type="checkbox" name="cashactive" id="activecash" value="Cash" checked style="font-weight: bold;font-size: 11px;">&nbsp;&nbsp;Cash
<input type="checkbox" name="creditactive" id="activecredits" value="Credit" style="font-weight: bold;font-size: 11px;">&nbsp;&nbsp;Credit<br>
</div>
</div>
</div>

if ($('#activecash').find('input[type=checkbox]:checked').length == 0) {
document.getElementById('errfnBC9').style.display = "block";
document.getElementById('errfnBC9').innerHTML = "**Please select at least one checkbox";
return false;
}

Answer Source

use only with javascript or jquery .Apply with onchange event it will validate each time of the box checking.

$(document).ready(function (){
 $('input[type=checkbox]').on('change',function (){
  if ($('input[type=checkbox]:checked').length == 0) {
     $('#errfnBC9').html( "**Please select atleast one checkbox");
    }
    else{
      
        $('#errfnBC9').html( "");
   
    }
  });
  });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row">
                        <div class="form-horizontal">
                            <label class="col-sm-5 control-label input-sm">Payement Type</label>
                            <div class="col-sm-5">
                                <span id="errfnBC9" style="color:red;font-size:8pt"></span><br>
                                <input type="checkbox" name="cashactive" id="activecash" value="Cash" checked style="font-weight: bold;font-size: 11px;">&nbsp;&nbsp;Cash
                                <input type="checkbox" name="creditactive" id="activecredits" value="Credit" style="font-weight: bold;font-size: 11px;">&nbsp;&nbsp;Credit<br>

                            </div>
                        </div>
                    </div>

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