pick up and save checkboxes checked with jquery and ajax

0

Hi, I have to collect the checkboxes that are checked to filter some results, I'm doing it through ajax.

<div class="form-group">
                  <label for="inputState"><strong>Estrellas</strong></label><br>
                  <label for="">1<input type="checkbox" name="ch" value="1" id="checkbox_uno"></label>
                  <label for="">2<input type="checkbox" name="ch" value="2" id="checkbox_dos"></label>
                  <label for="">3<input type="checkbox" name="ch" value="3" id="checkbox_tres"></label>
                  <label for="">4<input type="checkbox" name="ch" value="4" id="checkbox_cuatro"></label>
                  <label for="">5<input type="checkbox" name="ch" value="5" id="checkbox_cinco"></label>
                </div>
and this is the code of jquery

function estrellas(){

  var ckbox = $("input[name='ch']");
  var chkId = '';
  var ar=[];
  $('input:checkbox').on('click', function() {
    ar.splice(1,2);
    if (ckbox.is(':checked')) {
      $("input[name='ch']:checked").each ( function() {
        chkId = $(this).val();
        chkId = chkId.slice(0,-1);
        ar.push($(this).val());
      });
      console.log(ar);
      $.ajax({
      url:'php/ch.php',
      type:'POST',
      dataType:'JSON',
      data:{ch:JSON.stringify(ar)},
      success:function(resp){
      console.log(resp);
    },
    error:function(error){
    console.log(error);
  }
})
}
});
}
When I insert the ones that are checked in the array, I duplicate them and if I remove the check they keep saving me, any suggestions?     
asked by adrian ruiz picazo 16.05.2018 в 16:24
source

1 answer

0

I'll give you a more compact example of your function

var ar=[];
$("input:checkbox").change(function() {
   ar.length=0;
   $("input:checkbox").each ( function() {
      if ($(this).is(':checked')) {
         ar.push($(this).val());
      }
   });
   //aqui se añade tu funcion para guardar la info
});

I also leave the link for you to review link

    
answered by 16.05.2018 / 16:44
source