JavaScript CheckBox All [duplicate]

0

Personally I need to check all my system checkboxes using javascript, however I want to checkboxes through the id, how do I do this? I'm doing it this way, but it's not working:

function marcarTodos(marcar,cont){
    var id   = document.getElementById(cont);


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

        var i = 0;
        for(i=0; i<id.length;i++){

                id[i].checked = marcar;
        }
}
    
asked by anonymous 17.10.2016 / 13:31

2 answers

1

The second W3C, ID is a single attribute per page.

  

The id attribute specifies a unique id for an HTML element.

Law more in: HTML id Attribute

Therefore, you should use the NAME of the checkbox or a class to use them.

Below is a working example using the name to check or uncheck the checkboxes.

function marcarTodos(nome, marcar){
    var id   = document.getElementsByName(nome);
    
    
        if(marcar){
            document.getElementById('acao').innerHTML = 'Clicou em marcar Todos';
        }else{
            document.getElementById('acao').innerHTML = 'Clicou em desmarcar Todos';
        }

        var i = 0;
        for(i=0; i<id.length;i++){
              
                id[i].checked = marcar;
        }
    }
  <input type="checkbox" name="veiculo" value="Bicicleta"> Bicicleta<br>
  <input type="checkbox" name="veiculo" value="Carro" > Carro<br>
<input type="checkbox" name="veiculo" value="Moto" > Moto<br>

<br/>
<button onclick="javascript:marcarTodos('veiculo', true);">Marcar todos</button>
<button onclick="javascript:marcarTodos('veiculo', false);">Desmarcar todos</button>

<div id="acao"></div>
    
17.10.2016 / 14:37
1

Using Jquery you can search all the checkboxes inside a given element (or the entire page) and check all of them:

<html>

<div id="teste" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
</div>
<button title="Marcar" id="marcar"> Marcar </button>
   <script>
    var marcado = false;
    $('#marcar').on("click", marcaChecks);

    function marcaChecks(){
    $('#teste').find('input[type=checkbox]').each(function(indice,elemento){
    elemento.checked = !marcado;
    });
    marcado = !marcado;
    }
</script>
</html>

I used a global variable to store whether the checks should be checked or unchecked, if you reverse one by one as the question suggests, in the comment you would reverse all the checks.

Link working .

    
17.10.2016 / 14:38