Check/Deselect Checkbox from a button

Asked

Viewed 57,425 times

11

I would like to use a button to mark/uncheck checkbox. I have this button that calls a function, look:

<button 
  class='btn btn-large' 
  type='button' 
  title='Todos' 
  id='todos' 
  onclick='marcardesmarcar();'>
    <i class='icon-large icon-ok'></i>
</button>

The function:

function marcardesmarcar(){
  $('.marcar').each(
         function(){
           if ($(".marcar").prop( "checked")) 
           $(this).attr("checked", false);
           else $(this).attr("checked", true);               
         }
    );
}

The checks are that way:

<input type='checkbox' class='marcar' name='check[]'/>

This script makes it right the first time, but the second time it does nothing.

  • If I’m not mistaken, the attribute checked HTML (which corresponds to .attr("checked")) leaves the box marked independent of the attribute value only because the attribute is declared. I think <input type="checkbox" checked="false" /> tag line.

  • 2

    It would be nice if you evaluated the best answer to give the Accept, ("answer accepted" sign, in green) and then applied in the chosen answer, only once. It must be the third time I enter here and your "Accept" has moved. See more on this link: How and why to accept an answer

  • 1

    I endorsed as the best the answer of Anderson Pierok, but thank you for the warning, I will be more prudent in evaluating and only after selecting the best answer.

7 answers

17


Test like this:

function marcardesmarcar(){
    $(".marcar").each(
        function() {
            if ($(this).prop("checked")) {
                $(this).prop("checked", false);
            } else {
                $(this).prop("checked", true);
            }
        }
    });
}
  • Perfect, thanks for the collaboration.

  • 1

    I guess that would make every check alternate, huh? I mean, if half of the checks are checked and half of the checks are unchecked, it will reverse everything, instead of marking them all equally, or unchecking them all at once.

  • Thanks for the remark @bfavaretto.

  • There has been some change in the script?

  • 1

    Yes, if was incorrect, noted by @bfavaretto and I changed it.

  • 2

    @adventistapr Click on the "edited" link just below the reply to see the editions that have been made.

  • Thanks for the tip, but now I have a strange behavior, I mark all and right after I cancel one and I dial all checks are alternating.

  • 2

    @adventistapr If what you want is a function to mark or uncheck all (and not toggle the state of each one), a button is not the best interface solution. It would be clearer to use another checkbox: if it is checked, all are checked as well; if it is unchecked, all are unchecked. So imagine, with the button, what happens when you manually dial almost all checkboxes and then click on the button. What’s to happen? Mark the missing ones, or uncheck them all? What if you just check one manually?

  • It is correct very dear bfavoretto, including I took for me this indicated solution, thank you very much.

Show 4 more comments

13

The problem is that in if you should test the this, and not a collection of elements:

function marcardesmarcar() {
    $('.marcar').each(function () {
        if (this.checked) this.checked = false;
        else this.checked = true;
    });
}

Being tested $('.marcar').prop("checked")within the if, as soon as an item has been changed if will give true. I assume you want to test the element being traversed/iterated.

Example: http://jsfiddle.net/H544C/1/

  • Hello Sergio, thank you for the reply, please do the following test in your example, click to mark all checks and then click to uncheck, this will work the first time, the second no longer.

  • @adventistapr, corrected. This is what you want?

  • 1

    That’s right Sergio, thank you so much for your great help.

7

With pure javascript you can take the element by name and assign the checked value of marcar/desmarcar todos the others in onclick(), because getElementsByName() returns an array.

<script type="text/javascript">
    function marcarTodos(marcar){
        var itens = document.getElementsByName('cores[]');

        if(marcar){
            document.getElementById('acao').innerHTML = 'Desmarcar Todos';
        }else{
            document.getElementById('acao').innerHTML = 'Marcar Todos';
        }

        var i = 0;
        for(i=0; i<itens.length;i++){
            itens[i].checked = marcar;
        }

    }
</script>
<form>
    <input type="checkbox" name="cores[]" onclick="marcarTodos(this.checked);">
     <span id="acao">Marcar</span> <br>
    <input type="checkbox" name="cores[]" value="azul"> azul <br>
    <input type="checkbox" name="cores[]" value="verde"> verde <br>
    <input type="checkbox" name="cores[]" value="branco"> branco <br>
</form>

4

$("#MarcarTodos").click(function(){
        if ($(this).prop( "checked")){ 
            marcardesmarcar(true);
        }else{
            marcardesmarcar(false);
        }
    });

    function marcardesmarcar(bool){
      $('.marcar').each(
            function(){
               $(this).prop("checked", bool);            
             }
        );
    }

3

I created the same script in a simpler way:

marcarTodosCheckBoxes: function (seletorCheckBoxes) {
        $(this).prop('checked', !$(this).prop('checked'));
        $(seletorCheckBoxes).prop("checked", $(this).prop("checked"));
    }

2

Good night!

I’m setting up a library of events Jquery to be used in any project, and I was able to create that same script that way:

$(document).ready(function(){

   $("#ckAll").click(function()  {  // minha chk que marcará as outras

if ($("#ckAll").prop("checked"))   // se ela estiver marcada... 

$(".chk").prop("checked", true);  // as que estiverem nessa classe ".chk" tambem serão marcadas
     else $(".chk").prop("checked", false);   // se não, elas tambem serão desmarcadas

   });
}); 

It works perfectly, and I believe it to be simple and objective! improved on the basis of the above examples...

1

<script type="text/javascript">
    function marcarTodos(marcardesmarcar){
        $('.marcar').each(function () {
            this.checked = marcardesmarcar;
        });
    }
</script>
<form>
    <input type="checkbox" name="cores[]" onclick="marcarTodos(this.checked);">
     <span id="acao">Marcar</span> <br>
    <input type="checkbox" class="marcar" name="cores[]" value="azul"> azul <br>
    <input type="checkbox" class="marcar" name="cores[]" value="verde"> verde <br>
    <input type="checkbox" class="marcar" name="cores[]" value="branco"> branco <br>
</form>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.