mercredi 22 avril 2015

Multiple checkbox groups - alert if any are empty

I have a group of checkboxes with a jquery script that will change the background color of the container div if all of them are unselected. This works fine but there are several differently named checkbox groups on the page and at the moment I have a separate script for each of these.

I have been trying to put together a single script which would cover them all but only trigger the relevant ones. The main difficulty I am finding is replacing document.querySelectorAll('.xscheck') with something that will check only the checkboxes in the same group that has been clicked.

If anyone can give me any pointers, I would be eternally grateful, Or at least quite happy!

Thanks in advance

Steve

HTML

<div class="xs">
  <div class="">
    <input id="xscheck1" type="checkbox" name="xsLevel[]" class="xscheck" value="1" checked="">
    <label for="xscheck1">50</label>
  </div>
  <div class="">
    <input id="xscheck2" type="checkbox" name="xsLevel[]" class="xscheck" value="2" checked="">
    <label for="xscheck2">100</label>
  </div>
  <div class="">
    <input id="xscheck3" type="checkbox" name="xsLevel[]" class="xscheck" value="3" checked="">
    <label for="xscheck3">150</label>
  </div>
  <div class="">
    <input id="xscheck4" type="checkbox" name="xsLevel[]" class="xscheck" value="4" checked="">
    <label for="xscheck4">200</label> 
  </div>
</div>

JS

$('.xscheck').click(function(){
var textinputs = document.querySelectorAll('.xscheck'); 
var empty = [].filter.call( textinputs, function( el ) {
return !el.checked
});

if (textinputs.length == empty.length) {
    $('div.xs').addClass('bg-danger');
    $('.xs .noneselectederror').css("display", "block");
}else {
    $('div.xs').removeClass('bg-danger');
    $('.xs .noneselectederror').css("display", "none");
}
});




Aucun commentaire:

Enregistrer un commentaire