Button to check and uncheck all checkboxes

0

First, there's this question about Mark / Uncheck all checkboxes except the disabled , however I do not want it to clear what is already marked when clicking again. I want the button to uncheck all checkboxes , but if it has any checked, it should remain marked.

The idea is to check if most checkboxes are checked, then uncheck them. Otherwise, mark them.

I have the following code, see:

$(document).on("click", "#checkAll", function(){
    $('input[type="checkbox"]').prop("checked",  true);      
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><table><tr><td><inputtype="checkbox"/>Jon Snow</td>
    </tr>
    <tr>
        <td><input type="checkbox"/>Tony Stark</td>
    </tr>
    <tr>
        <td><input type="checkbox"/>Paul McCartney</td>
    </tr>
    <tr>
        <td><input type="checkbox"/>Luke Skywalker</td>
    </tr>
     <tr>
        <td><input type="checkbox"/>Pablo Escobar</td>
    </tr>
</table>

 <button style="float: left;" type="button" class="btn btn-default btn-xs" id="checkAll">Botão</button>

I would like to click again to uncheck checkboxes . What would be the best way to do this?

    
asked by anonymous 07.08.2017 / 17:10

1 answer

0

The question was not very clear so I managed to do this, check if you answered and if not post the comment so I can help you.

$(function(){
  $('#checkAll').click(function(){
    let desmarcados = $('input:checkbox:not(:checked)').length;
    let marcados = $('input:checkbox:checked').length;
    console.log(marcados);
    console.log(desmarcados);
    if(marcados > desmarcados){
       $('input:checkbox').prop("checked", false);
    }else{
      $('input:checkbox').prop("checked", true);
    }
    
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><table><tr><td><inputtype="checkbox"/>Jon Snow</td>
        </tr>
        <tr>
            <td><input type="checkbox"/>Tony Stark</td>
        </tr>
        <tr>
            <td><input type="checkbox"/>Paul McCartney</td>
        </tr>
        <tr>
            <td><input type="checkbox"/>Luke Skywalker</td>
        </tr>
    </table>

     <button style="float: left;" type="button" class="btn btn-default btn-xs" id="checkAll">Marcar tudo</button>
    
07.08.2017 / 17:33