Javascript Checkbox All

Asked

Viewed 196 times

0

Personal need to mark all checkbox of my system using javascript, however want to mark the checkbox through 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;
        }
}
  • You are using Jquery or need to be pure Javascript ?

  • Hello Lucas, I’m using pure js but can be in both.

2 answers

1

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

The id attribute specifies a Unique id for an HTML element (the value must be Unique Within the HTML Document).

Law more in: HTML id Attribute

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

Below is a functional example using the name to mark or deselect 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>

1

Using Jquery you can search all checkboxes within a given element (or the whole 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 save if checks should be marked or unchecked, if you invert one to one as the question suggests, in the comment you would invert all checks.

Link working.

Browser other questions tagged

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