Checkbox that selects all

Asked

Viewed 2,540 times

1

I have a list of several checkboxes, and wanted the last checkbox to be to select and de-select all others. Example:

if (document.getElementById("all").checked = true){
    //selecionar todas
}

if (document.getElementById("all").checked = false){
   //des-selecionar todas
}
1<input type="checkbox"  id=1 name=1>
2<input type="checkbox"  name=2>
3<input type="checkbox"  name=3>
4<input type="checkbox"  name=4>
5<input type="checkbox"  name=5>
<p>Todas<input type="checkbox"  id=all name=all></p>

  • That example could also be better built...

  • What is your question? Is it how to select all checkboxes for marking? Is it how to make them check? Something else?

  • is to mark and uncheck all checkboxes with only the last checkbox. I edited jsfiddle.

  • 1

    @akm, have you noticed that all your html is poorly built? Quotation marks are missing" on each element..

4 answers

3


Select the checkbox desired, and assign it the function onclick:

document.querySelector("input[name=all]").onclick = function() {

Select the others checkboxes (in your example are all, but the ideal would be to use classes for this):

    var lista = document.querySelectorAll("input");

Walk them

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

And assign your property checked for true.

        lista[i].checked = true;
};

Full example. If instead you want to either mark or uncheck (depending on whether the latter is checked or not) then you need to first select the new value:

document.querySelector("input[name=all]").onclick = function(e) {
    var marcar = e.target.checked; // A verificação ocorre depois que o valor já mudou

And then use it on the others checkboxes:

    var lista = document.querySelectorAll("input");
    for ( var i = 0 ; i < lista.length ; i++ )
        lista[i].checked = marcar;
};

Updated example.

  • how could I resolve this my http://answall.com/questions/178790/comorenviar-checkbox-com-names-diferentes-para-o-mysql

2

You can do this by Javascript, associating the action to a main Checkbox that will select all the others. Here’s an example, where you select all Checkboxes by the CSS class checkbox1:

<input type="checkbox" id="selecctall"/> Selecionar tudo
<br /><input class="checkbox1" type="checkbox" name="check[]" value="item1"> Item 1
<br /><input class="checkbox1" type="checkbox" name="check[]" value="item2"> Item 2
<br /><input class="checkbox1" type="checkbox" name="check[]" value="item3"> Item 3
<br /><input class="checkbox1" type="checkbox" name="check[]" value="item4"> Item 4
<br /><input class="checkbox1" type="checkbox" name="check[]" value="item5"> Item 5
<br /><input class="checkbox1" type="checkbox" name="check[]" value="item6"> Item 6
<br /><input class="checkbox2" type="checkbox" name="check[]" value="item6"> Esta não seleciona

Javascript:

$(document).ready(function() {
    $('#selecctall').click(function(event) {  //on click 
        if(this.checked) { // check select status
            $('.checkbox1').each(function() { //loop through each checkbox
                this.checked = true;  //select all checkboxes with class "checkbox1"               
            });
        }else{
            $('.checkbox1').each(function() { //loop through each checkbox
                this.checked = false; //deselect all checkboxes with class "checkbox1"                       
            });         
        }
    });

http://jsfiddle.net/fjnw4w3L/3/

1

Other users have already provided interesting solutions, but here is an alternative if you find interesting, I will put in javascript and jquery:

Inversion of Selections

JQUERY

$(document).on('click', '#all', function (e) {
    $('input[type="checkbox"]').not('#all').each(function() {
        var checked = $(this).is(':checked');
        checked ? $(this).prop('checked', false) : $(this).prop('checked', true);
    });
});

JAVASCRIPT

document.getElementById("all").addEventListener("click", function(){
    checkBoxs = document.querySelectorAll('input[type="checkbox"]:not([id=all])');
    //"Hack": http://toddmotto.com/ditch-the-array-foreach-call-nodelist-hack/
    [].forEach.call(checkBoxs, function(checkbox) {
        checkbox.checked = checkbox.checked ? false : true;
    });
});

Example: https://jsfiddle.net/1Lxwsae3/3/

EDIT

Select/Unselect All

var checkedAll = false;

//JQUERY
$(document).on('click', '#all', function (e) {
    $('input[type="checkbox"]').not('#all').each(function() {
        //Verificamos se é a hora de dar checked a todos ou tirar;
        checkedAll ? $(this).prop('checked', false) : $(this).prop('checked', true);
    });
    //Invertemos ao final da execução, caso a última tenha sido true para checar todos, tornamos ele false para o próximo clique;
    checkedAll = checkedAll ? false : true;
});

//JAVASCRIPT
document.getElementById("all").addEventListener("click", function(){
    checkBoxs = document.querySelectorAll('input[type="checkbox"]:not([id=all])');
    //"Hack": http://toddmotto.com/ditch-the-array-foreach-call-nodelist-hack/
    [].forEach.call(checkBoxs, function(checkbox) {
        //Verificamos se é a hora de dar checked a todos ou tirar;
        checkbox.checked = checkedAll ? false : true;
    });
    //Invertemos ao final da execução, caso a última tenha sido true para checar todos, tornamos ele false para o próximo clique;
    checkedAll = checkedAll ? false : true;
});

Example: https://jsfiddle.net/ze9qo4yu/1/

If you have any questions or are not what you are looking for, please let us know.

  • 2

    It won’t just go reverse the selection of each individual checkbox? What the AP asked was that when clicking "all" all others were marked or unmarked, regardless of their current selection.

  • 1

    @mgibsonbr Thank you, well noted, nor had I realized that I fled the question, I will make another example focused on the need of the user.

0

Solved:

function marcarTodos(marcar){
    var itens = document.querySelectorAll("input");

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

Browser other questions tagged

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