Miguel Osorio Miguel Osorio - 4 months ago 13
HTML Question

Array Checkbox validation in jquery

I want to validate an Array checkbox using Jquery, but i dont know how validate the checkbox using jquery... this is my code

<div class="col-sm-8">
<label class="checkbox-inline"><input type='checkbox' name='checkboxvar[]' value='0' id='checkboxvar[]'>L</label>
<label class="checkbox-inline"><input type='checkbox' name='checkboxvar[]' value='1' id='checkboxvar[]'>M</label>
<label class="checkbox-inline"><input type='checkbox' name='checkboxvar[]' value='2' id='checkboxvar[]'>Mi</label>
<label class="checkbox-inline"><input type='checkbox' name='checkboxvar[]' value='3' id='checkboxvar[]'>J</label>
<label class="checkbox-inline"><input type='checkbox' name='checkboxvar[]' value='4' id='checkboxvar[]'>V</label>
</div>

<script>
function validate() {
if($("#checkboxvar").is(':checked')) {
alert("actived");
} else {
alert("No actived");
}
}
</script>

Answer

First of all remove the id duplication. Id should be unique per page.

Demo : https://jsfiddle.net/Prakash_Thete/bdjue21w/

If you want to check which checkbox is checked on validate you can just apply common class to all of them and then traverse over it and check if any one of them is checked.

Like below

 function validate() {
    $(".checkboxvar").each(function(index){
       if($(this).is(':checked')){
        alert("checked element value : " + + $(this).val());
       } else{
       alert("unchecked element value: " + $(this).val());
       }
 });
 }

Assuming HTML to be like this :

<div class="col-sm-8">
  <label class="checkbox-inline"><input type='checkbox' name='checkboxvar[]' value='0' class='checkboxvar'>L</label>
  <label class="checkbox-inline"><input type='checkbox' name='checkboxvar[]' value='1' class='checkboxvar'>M</label>
  <label class="checkbox-inline"><input type='checkbox' name='checkboxvar[]' value='2' class='checkboxvar'>Mi</label>
  <label class="checkbox-inline"><input type='checkbox' name='checkboxvar[]' value='3' class='checkboxvar'>J</label>
  <label class="checkbox-inline"><input type='checkbox' name='checkboxvar[]' value='4' class='checkboxvar'>V</label>
</div>