select several checkboxes when filtering the result by AJAX

0

I need to select several checkboxes that are not together and put them in a input type text , I achieved that by filtering "states" and selecting them I put them in input .

But when doing another search, delete the checkbox previously chosen.

Script to dynamically search for states

<script>
  function buscar() {
    var textoBusqueda = $("input#busqueda").val();
    if (textoBusqueda != "") {
      $.post("prueba_buscar.php", {valorBusqueda: textoBusqueda}, function(mensaje) {
        $("#resultadoBusquedaEstado").html(mensaje);
      }); 
    } 
    else { 
      p= "_";
      $.post("prueba_buscar.php", {valorBusqueda: p}, function(mensaje) {
        $("#resultadoBusquedaEstado").html(mensaje);
      });
    };
  };
</script>

Script to group selected checkbox

<script>
$(document).ready(function(){
  $('.check').click(function() {
    var ids;
    ids = $('input[type=checkbox]:checked').map(function() {
    return $(this).attr('id');
   }).get();

   $('#status1').val(ids.join(', '));
  });
});
</script>
    
asked by Agus Olivera 06.01.2018 в 00:30
source

1 answer

2

How are you saving the ids of those already selected, when you add the checkboxes with the .html() method, iterate over each id to find the checkbox and mark it:

<script>

$(document).ready(function(){
   var ids = []

  $('.check').click(function() {  
    ids = $('input[type=checkbox]:checked').map(function() {
    return $(this).attr('id');
   }).get();

   $('#status1').val(ids.join(', ')); 
  });


  function marcarSeleccionados(){
        // iteramos cada id de los seleccionados
        for(var i = 0; i < ids.length;i++)
        {
            // buscamos el checkbox y lo marcamos
            $("#"+ids[i]).attr("checked",true);
        }
   }

  window.buscar = function() {
    var textoBusqueda = $("input#busqueda").val();
    if (textoBusqueda != "") {
      $.post("prueba_buscar.php", {valorBusqueda: textoBusqueda}, function(mensaje) {
        $("#resultadoBusquedaEstado").html(mensaje);
        marcarSeleccionados();
      }); 
    } 
    else { 
      p= "_";
      $.post("prueba_buscar.php", {valorBusqueda: p}, function(mensaje) {
        $("#resultadoBusquedaEstado").html(mensaje);
        marcarSeleccionados();
      });
    };
  };

});
</script>
    
answered by 06.01.2018 в 01:22