How to select the ids of a table with checkbox and save in the bank?

1

How do I select some items from a dimanic table coming from the mysql database and loaded into a table using javascript or jquery and set the marked checkboxes to the category as 'sport' in the database? Below is an outline of the code

<table border="1">
  <thead>
      <tr>
        <th>Id</th>
        <th>Nome</th>
        <th>Categoria</th>
        <th>Editar</th>
      </tr>
  </thead>
  <tbody>
      <tr>
        <td><input type="checkbox" id="<?php echo $id ?>" value="<?php echo $id ?>"></td>
        <td>Fifa 2017</td>
        <td>Não definido</td>
        <td><button name="Editar">Editar</button></td>
      </tr>
      <tr>
        <td><input type="checkbox" id="<?php echo $id ?>" value="<?php echo $id ?>"></td>
        <td>Formula 1</td>
        <td>não definido</td>
        <td><button name="Editar">Editar</button></td>
      </tr>
  </tbody>
</table>

In the example above I want to select the two items and edit them so that the category is a sport.

I think of retrieving the ids of the selected checkboxes and writing to an Array () and then picking up this Array () and updating the database with the data.

I need to select multiple and edit only once and not line by line.

    
asked by anonymous 03.05.2017 / 17:29

1 answer

2

You'll then collect the IDs you want to change, then send the new array with IDs for your PHP saved in the database.

function coletaDados(){
   var ids = document.getElementsByClassName('editar');
   coletaIDs(ids);         
}  
        
function coletaIDs(dados){
   var array_dados = dados; 
   var newArray = [];
   for(var x = 0; x <= array_dados.length; x++){     
        if(typeof array_dados[x] == 'object'){
          if(array_dados[x].checked){
             newArray.push(array_dados[x].id)          
          }          
        }
   }
  if(newArray.length <= 0){
    alert("Selecione um pelo menos 1 item!");     
  }else{
    alert("Seu novo array de IDs tem os seguites ids [ "+newArray+" ]");
  }  
}
<table border="1">
  <thead>
      <tr>
        <th>Id</th>
        <th>Nome</th>
        <th>Categoria</th>
      </tr>
  </thead>
  <tbody>
      <tr>
        <td><input class="editar" type="checkbox" id="01" value="Fifa"></td>
        <td>Fifa 2017</td>
        <td>Não definido</td>
      </tr>
      <tr>
        <td><input class="editar" type="checkbox" id="02" value="Formula 1"></td>
        <td>Formula 1</td>
        <td>não definido</td>
      </tr>
    <tr>
      <td colspan="3">
        <button style="width:100%;" onclick="coletaDados()">Editar</button>
      </td>
    </tr>
  </tbody>
</table>
    
04.05.2017 / 05:09