Select All checkbox by clicking a checkbox

Asked

Viewed 1,977 times

2

I looked for the solution here in the forum, however they did not work.

I want to select all the checkbox by clicking only 1 checkbox (selects all).

Follows my code:

   <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


    <link rel="stylesheet" href="css/app.min.css">

    <meta name="description" content="Violate Responsive Admin Template">
    <meta name="keywords" content="Super Admin, Admin, Template, Bootstrap">

     <script>
        $(document).ready(function(){ 
          //Para fins de depuração:
          console.log("Entrei aqui.");
            $("#checkMaster").click(function(){
            //Para fins de depuração:
            console.log("Checkbox mestre foi clicado!");    
                $('input:checkbox').not(this).prop('checked', this.checked);
            });
            console.log("saiu aqui.");
        });

    </script>

<!--    <meta http-equiv="refresh" content="5" /> -->
  </head>  

Warning

             <div class="card">
                <div class="card-body">


                    <div class="table-responsive">
                        <table id="data-table" class="table">
                            <thead>
                                <tr>
                                    <th>Nome</th>
                                    <th>Telefone</th>
                                    <th>Numero de tentativas</th>
                                    <th>Ultima Tentativa</th>
                                    <th>Zerar Tentativas?</th>

                                </tr>
                            </thead>
                            <tbody>
                                <tr>
                                    <td></td>
                                    <td></td>
                                    <td></td>
                                    <td></td>
                                    <td><p><input type="checkbox" id="checkMaster" name="checkTodos"> Selecionar Todos</p></td>

                                </tr>
                                <?php 

                                    $query = sprintf("select * from ivr_contatos, ivr_campanha where ivr_contatos.campanha = ivr_campanha.id and ivr_contatos.status = 0 and tentativas >= 5" );
                                    $result = Populator::ConsultaDB($query);

                                    while ($resultado = pg_fetch_array($result) ) {
                                        $nome = $resultado['nome'];
                                        $telefone = $resultado['telefone'];
                                        $tentativa = $resultado['tentativas'];
                                        $lastAttempt = $resultado['atualizado'];
                                        $codigo = $resultado['codigo'];

                               echo '         

                                <tr>
                                    <td>'.$nome.'</td>
                                    <td>'.$telefone.'</td>
                                    <td>'.$tentativa.'</td>
                                    <td>'.substr($lastAttempt,0,19).'</td>
                                    <td><input type="checkbox" value='.$codigo.' name="check[]"/></td>
                                </tr>
                                ';
                                    }
                                ?>

                            </tbody>
                        </table>
                    </div>
                </div>
            </div>

            <input type="submit" value="Resubmit" class="btn btn-sm m-r-5" />

        </form>

Any idea how to fix this??

Edit: Dear, good afternoon, I realized the recommendations of this post, however I’m still with the same problem. Is there any other way I can go to achieve this goal?

Follows console print: inserir a descrição da imagem aqui

$('input:checkbox').not(this).prop('checked', this.checked);
init(16) [input#ckball, input#ckbCod.check, input#ckbCod.check, input#ckbCod.check, input#ckbCod.check, input#ckbCod.check, input#ckbCod.check, input#ckbCod.check, input#ckbCod.check, input#ckbCod.check, input#ckbCod.check, input#ckbCod.check, input#ckbCod.check, input#ckbCod.check, input#ckbCod.check, input#ckbCod.check, prevObject: init(16), context: document]
  • 1

    The code seems ok to me! What is not working?

  • When I click on the checkbox select all, the others are not marked as checked

  • Your code is working, see here https://jsfiddle.net/Lwamk47c/

  • Try to put the code inside $(document).ready(function(){ código aqui });

  • I tried, but tbm didn’t roll, I’m excited about it man, jsfiddle works, web page does not...

  • See if it shows an error in the console by clicking the boss checkbox

  • On the console this showing error on this line $('input:checkbox').(this). prop('checked', this.checked); shows this error, but I can’t find it. Uncaught Syntaxerror: Unexpected token (

  • That one .(this) is wrong... the correct is $('input:checkbox').prop('checked', this.checked);

  • I made the change, the error in the console is gone, but it does not select the other checkbox

  • Are you sure there is only 1 id with "checkTodos"?

  • go to the console and run $("#checkTodos").length... if return more than 1 there is bad

  • Executed, he returned only 1

  • 1

    So the only output is vc show the whole code, only the part that involves javascript and the table.

  • posted in response.

  • With the $(document).ready(function(){ worked

  • $(document).ready(function(){&#xA; $("#checkTodos").click(function(){&#xA; $('input:checkbox').prop('checked', this.checked);&#xA; });&#xA; });

  • I made the change, however it persists... Maybe, the bootstrap hides when the others are checked? or it would have no influence?

  • Caique, I performed the tests, and he returns the following information to console.log( $('input:checkbox').not(this).prop('checked') ); = false; console.log( $('input:checkbox').not(this) ); VM2617:1 init(16) [input#ckball, input#ckbCod.check, input#ckbCod.check, input#ckbCod.check, input#ckbCod.check, input#ckbCod.check, input#ckbCod.check, input#ckbCod.check, input#ckbCod.check, input#ckbCod.check, input#ckbCod.check, input#ckbCod.check, input#ckbCod.check, input#ckbCod.check, input#ckbCod.check, input#ckbCod.check, prevObject: init(16), context: Document]

  • @Caiqueromero then, the question of the ID is how this checkbox is generated whenever a new record is made in the bank.

  • You put fixed <td><input type='checkbox' id='ckbCod'></td> this is within a loop, so your html will contain several <input /> with even id understands?

  • Yes.. but this would be a necessity of the application pq whenever there is a record in the database would be created a checkbox for it. Is there no way I can select all checkboxes even with the same ID? or create a dynamic ID?

  • @Caiqueromero he comes to rotate, I will put in the question for you see the answer

  • by the console it shows that this as checked but visually not shown

Show 19 more comments

4 answers

1

  • The error still persists. for some reason, it does not select the rest of the checkbox

1

Follow below example with your own code, the same worked perfectly.

To complement your code I added a check on <tr> of <table>, this way if the user click on the respective line checkbox will be marked.

$(document).ready(function(){ 
  //Para fins de depuração:
  console.log("Entrei aqui.");

  $("#checkMestre").click(function(){

    //Para fins de depuração:
    console.log("Checkbox mestre foi clicado!");
    
    $('input:checkbox').not(this).prop('checked', this.checked);
  });

  //Função para marcar o checkbox ao clicar na linha:
  $("#exemplo tr").on("click", function(){
    $(this).children().children()[0].click();
  });

  //Impeço a propagação para não dar conflito com o click na tr.
  $("input:checkbox").on("click", function(e){
    e.stopPropagation();
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<table id="exemplo">
  <thead>
    <tr>
      <th>
        <input type="checkbox" id="checkMestre"/>
      </th>
      <th>
        Nome
      </th>
      <th>
        Nível
      </th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>
        <input type="checkbox" id="idUsuario" value="1"/>
      </td>      
      <td>
        Caique
      </td>
      <td>
        Prata
      </td>
    </tr>
    <tr>
      <td>
        <input type="checkbox" id="idUsuario" value="2"/>
      </td>      
      <td>
        Natane
      </td>
      <td>
        Ouro
      </td>
    </tr>
  </tbody>
</table>

  • Thanks Caique, however not rolled yet.. I still select only 1 checkbox instead of all...

  • The problem persisted, I’m thinking it might be something from bootstrap

  • in head are only libraries and jquery script...

  • Caique, it was my first idea, I changed it, but it didn’t work.

  • I made the change, but did not call any Alert

1

Your code is correct and functional. The problem is that you are loading the click event before PHP renders the table elements.

It is necessary that the event is loaded after the DOM is ready. To do so include the code within the event ready:

$(document).ready(function(){
   $("#checkTodos").click(function(){
      $('input:checkbox').prop('checked', this.checked);
   });
});

You can also put the script inline direct in the tag with the event onclick, then you don’t need the $(document).ready:

<input onclick="$('input:checkbox').prop('checked', this.checked);" type="checkbox" id="checkTodos">
  • I included $(Document). ready(Function(){} as reported, however the problem persists. & #Xa;sera has something to do with using the bootstrap by hiding the other checkbox checked?

  • puts an Alert("ok"); inside the click event to see if it appears.

  • It did not appear, so there is no checkbox connection with jquery

  • That’s right, but make Document ready as is

  • Change the event to this: $(document).on("click", "#checkTodos", function(){

  • I changed, but not changed, not yet displayed the ok alert

  • he makes the call through the correct ID? I will change the ID and test

  • It won’t do no good... remove all plugins and libraries, everything, just leave jQuery’s <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

  • At first I can say with certainty that the problem is that of my answer even, without the ready Document the click does not work because the event is loaded before the table HTML... unless you put the script later, but do not need....

  • Do the following: take this same warningview.php file that you sent me and saved on the desktop and change the extension from . php to . html and open in the browser... the page will open all broken but no problem... go there where is the checkbox and test.

  • All right, I’ll test it here, and I’ll bring you the answer.

  • Really, brings the page all broken haha, but it worked, this selecting the check

  • Do the following, now right there on your PHP page: delete all this code that we are seeing ($("#checkTodos").click(function(){...) and puts the onclick right on the tag, like this: <input onclick="$('input:checkbox').prop('checked', this.checked);" type="checkbox" id="checkTodos">

  • I made the change, but no changes occurred

  • I deleted all the jquery script and added this line where the checkbox would be, that would be the procedure?

  • Stayed like this? <input onclick="$('input:checkbox').prop('checked', this.checked);" type="checkbox" id="checkTodos">

  • that, that’s how

  • Blz... I’ll switch to pure JS.. Perai

  • I tried to do through a button even by a pure JS Function, but tbm did not roll... I think something blocks the command or the passing of information to the JS

  • forehead there: <input onclick="var els=document.querySelectorAll('input[type=checkbox]');for(var x=0;x<els.length;x++){els[x].checked=this.checked;}" type="checkbox" id="checkTodos">

  • Still nothing, man this is making me half goat... there’s no reason not to work, no error, and when converted to html works.

  • may be problem on the same server

  • vc is using local server on the machine itself or is hosted?

  • Using local, I use wamp

Show 19 more comments

0

Change in input checkbox:

<td><input type="checkbox" value='.$codigo.' name="check[]" class="check"/></td>

In the Jquery:

$('#checkMaster').click(function(){
    $.each($('.check'),function(){
      if($(this).is(':checked')){
        $(this).prop('checked',false);
      }else{
        $(this).prop('checked',true);
      }
    });
});
  • Oops, I’ll test that way

Browser other questions tagged

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