help with jquery to select table checkbox dynamically created c #

0

What friends have the following problem, I am generating a dynamic table with jquery result of a query to a method of c # the method is

 public JsonResult GetRequirentes(string term)
    {
        var Result = from c in db.MtoRequirentes
                     where c.Descripcion.ToString().Contains(term)
                     orderby c.Descripcion
                     select new Item
                     {
                         id = c.MtoRequirenteId.ToString(),
                         value = c.Descripcion.ToString()
                     };

        return Json(Result.Take(10).ToList(), JsonRequestBehavior.AllowGet);
    }

well to generate the table in html I use a function

function GetTableRequirentes(Id) {
if (Id > 0) {
    $('#tblRequirentes').show();
    $.ajax({
        cache: false,
        url: _urlBase + 'Requirentes/GetTableRequirentes',
        type: "GET",
        dataType: 'json',
        data: { id: Id },
        success: function (data) {
            var resultado = $.parseJSON(JSON.stringify(data.data));
            if (resultado.length > 0) {
                console.log(resultado);
                for (var i = resultado.length - 1; i >= 0; i--) {
                    var rows = "<tr>"

                        + "<td class='text-center'><input type='checkbox' id='" + resultado[i].MtoRequirenteId + "'class='case'>" + "</td>"                                                        
                        + "<td>" + resultado[i].Descripcion +"</td>"                            
                        + "</tr>";

                    $('#tblRequirentes tbody').append(rows);
                }
            }
            else {
                $('#FileUpload1').show();
                $('#Submit').show();
                $('#Resultado').hide();
            }
        },
        error: function (ex) {
            alert('Error al Cargar la información relativa a requirentes.' + ex);                
        }
    });
    return false;
}    

}

So here I have no problems, then I generate a function to be able to select all the checkboc in the table

$("#checkBoxAll").on("change", function () {

    $(".case").prop("checked", this.checked);
});

this method selects all the checkboxes that exist in the table, now what I want is that when I remove the selection from a chexkbox (since not all are selected) I remove the selection from the checboc that marks all.

I'm trying it this way but it does not work.

$(".case").on("change", function () {
    if ($(".case").length == $(".case:checked").length) {
        $("#checkBoxAll").prop("checked", true);
    } else {
        $("#checkBoxAll").prop("checked", false);
    }
});

They would be so kind as to give me a clue as to how I could solve this problem.

thanks

    
asked by Horacio Xochitemol 01.12.2018 в 14:45
source

1 answer

0

I have simulated your checkbox in a very simple way, and the truth that you have works well.

I leave what I've tried as you describe it:

$(function() {
    $("#checkBoxAll").on("change", function() {
        $(".case").prop("checked", this.checked);
    });

    $(".case").on("change", function() {
        if ($(".case").length == $(".case:checked").length) {
            $("#checkBoxAll").prop("checked", true);
        } else {
            $("#checkBoxAll").prop("checked", false);
        }
    });
});
<html>
<body>
  <input type="checkbox" id="checkBoxAll"> check all<br><hr>
  <input type="checkbox" class="case" id="checkBox1"> check 1<br>
  <input type="checkbox" class="case" id="checkBox2"> check 2<br>
  <input type="checkbox" class="case" id="checkBox3"> check 3<br>
  
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
</body>
</html>

If you look, depending on what you ask and the code you put in, it should work. But, since you are dynamically adding rows to the table, those new rows are no longer tied to the change event that you scheduled.

To solve it in a simple way you should implement it in this way:

$(document).on("change", ".case", function() {
    if ($(".case").length == $(".case:checked").length) {
        $("#checkBoxAll").prop("checked", true);
    } else {
        $("#checkBoxAll").prop("checked", false);
    }
});

This way every time you add a new row, you will subscribe to the event.

I also advise you to check that other input you are assigning the class case , most likely that may also be affecting or affect later ( if the project grows ) when you do the $(".case").length .

I'll give you an example of how you can always refer to the checkbox of a specific table, so if you have some other input with the class case will not take it into account.

$(function() {

  $("#checkBoxAll").on("change", function () {
      $("#tblRequirentes tbody input[type='checkbox'].case").prop("checked", this.checked);
  });
  
  $("#tblRequirentes tbody").on("change", "input[type='checkbox'].case", function () {
    if ($("#tblRequirentes tbody input[type='checkbox'].case").length == $("#tblRequirentes tbody input[type='checkbox'].case:checked").length) {
        $("#checkBoxAll").prop("checked", true);
    } else {
        $("#checkBoxAll").prop("checked", false);
    }
   });
   
});
<html>
   <body>
      <hr>
      <table id="tblRequirentes">
         <tbody>
            <tr>
               <td><input type="checkbox" id="checkBoxAll"> check all</td>
            </tr>
            <tr>
               <td><input type="checkbox" class="case" id="checkBox1"> check 1</td>
            </tr>
            <tr>
               <td><input type="checkbox" class="case" id="checkBox2"> check 2</td>
            </tr>
            <tr>
               <td><input type="checkbox" class="case" id="checkBox3"> check 3</td>
            </tr>
         </tbody>
      </table>
      <hr>
      <br>
      <input type="checkbox" class="case" id="checkBox4"> check 4 fuera de la tabla
      <br>
      <br>
      <input type="text" class="case">
   </body>
   <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
</html>
    
answered by 01.12.2018 в 15:49