if / else condition to mark / uncheck checkbox

1

I would like to know what a condition to uncheck all my ckeckbox .

function marcarDesmarcarTodos() {
    for (i = 0; i <= 500; i++) {
        document.getElementById('seleciona_ativarDesativar_'+i).checked = true;
    }
}

I tried it the following way, but it did not work.

function marcarDesmarcarTodos() {
    for (i = 0; i <= 500; i++) {
        if (document.getElementById('seleciona_ativarDesativar_'+i) != 'checked') {
            document.getElementById('seleciona_ativarDesativar_'+i).checked = true;
        } else {
            document.getElementById('seleciona_ativarDesativar_'+i).checked = false;
        }
    }
}
    
asked by anonymous 08.05.2015 / 16:02

3 answers

2

You need to get these checkbox , for example with:

document.querySelectorAll('input[type=checkbox]');

and then iterates them by changing the checked to false .

Now you have different options:

  • Reverse state
  • Force all / none

Invert status:

function marcarDesmarcarTodos() {
    var checkboxes = document.querySelectorAll('input[type=checkbox]');
    for (var i = 0; i < checkboxes.length; i++) {
        checkboxes[i].checked = !checkboxes[i].checked;
    }
}

jsFiddle: link

Force all / none

In this case you can use flag to save the state. It could also be saved in the input in a data-estado , but in the example I use a variable for it.

var estado = false;
function marcarDesmarcarTodos() {
    var checkboxes = document.querySelectorAll('input[type=checkbox]');
    for (var i = 0; i < checkboxes.length; i++) {
        checkboxes[i].checked = !estado;
    }
    estado = !estado;
}

jsFiddle: link

    
10.05.2015 / 06:07
0

You can use this function JS :

function marcarDesmarcar(source) {
  checkboxes = document.getElementsByName('foo');
  for(var i=0, n=checkboxes.length;i<n;i++) {
    checkboxes[i].checked = source.checked;
  }
}                   
<input type="checkbox" onClick="marcarDesmarcar(this)" /> Marcar e Desmarcar todos<br/>
  
<input type="checkbox" name="foo" value="bar1"> check 1<br/>
<input type="checkbox" name="foo" value="bar2"> check 2<br/>
<input type="checkbox" name="foo" value="bar3"> check 3<br/>
<input type="checkbox" name="foo" value="bar4"> check 4<br/>
    
08.05.2015 / 16:07
0

Search for the each function of JS, using jQuery ...

Its use is very simple:

$("input[type='checkbox']").each(function(){
     this.checked = false;
});

Example

    
08.05.2015 / 16:06