if/Else condition to mark/deselect checkbox

Asked

Viewed 2,230 times

1

I wonder what a condition it would be to cancel all my ckeckbox.

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

I tried it this way, but it didn’t 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;
        }
    }
}

3 answers

2

You need to get those checkbox, for example with:

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

and then burn them by changing the checked for false.

Now you have different options:

  • Reverse the state
  • Force all/ none

Reverse the state:

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

jsFiddle: http://jsfiddle.net/nwvgyd3d/

Force all/ none

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

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: http://jsfiddle.net/nwvgyd3d/1/

  • Sergio loves querySelectorAll right? aheuhaeuhae I’m amazed

  • 2

    @Maiconcarraro I decided a while ago not to use IE8 anymore, and qsa is to help me remember the decision :)

0

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

Its use is very simple:

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

Example

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/>

Browser other questions tagged

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