Get value from a table row if checkbox is checked

3

I have the following table which is built from a database entity.

HTML:

<table class="table table-hover" id="produtostab">
            <thead>
                <tr>
                    <th>Descrição</th>
                    <th>Quantidade</th>
                    <th>Selecionar</th>
                </tr>
            </thead>
            <tbody id="myTable">
                <?php
                    $conn = new mysqli('localhost', 'root', '', 'exemplo') or die ('Falha ao conectar-se com DB');
                    mysqli_query($conn, "SET NAMES 'UTF8'") or die("ERROR: ". mysqli_error($con));
                    $result = $conn->query("select idProduto, Descricao from produto");
                    while ($row = $result->fetch_assoc()) {
                        unset($idProduto, $Descricao);
                        $idProduto = $row['idProduto'];
                        $Descricao = $row['Descricao'];
                        echo '<tr>'; 
                        echo '<td>'.$Descricao.'</td>';
                        echo '<td contenteditable="true"></td>';
                        echo '<td><input type="checkbox"></td>';
                        echo '</tr>';
                    }
                    ?>
            </tbody>
    </table>

In each row of the table, there is a checkbox. I need, after pushing a submit button, the content of all the rows that are checked (from the checkbox) to be stored in a PHP array to be queried later. How could he do that? I do not know if it is possible, if it is not, is there another way to get the values of these rows checked?

    
asked by anonymous 21.08.2014 / 20:18

1 answer

6

I do not know if it's better or if that's the case, but I thought of a solution with jQuery

$(document).ready(function(){
    var total = [];
    $("tr").each(function(){
        total.push("");
    });

    $("input").click(function(){    
        var index = $(this).closest("tr").index();
        if($(this).prop('checked')){
            total[index] = $(this).parent().parent().find("td:first-of-type").text();
            $(".result").html(total);
        } else {
            total[index] = "";    
            $(".result").html(total);        
        }
    });
 });

First I create the array and add an entry for each row of the table. I do this to be able to handle those entries later.

I'm doing it on the click of the checkbox, but of course you should change it as you see fit to improve usability.

When you have the checkbox click, it checks the number of this row of the table and stores it in the index variable. Then he sees if the checkbox is checked or not.

If yes, it adds the value to the same point in the array of the line in question (so you had to create everything first). If not, it leaves it blank. I tried to use .push and .split, but then the array changes size and I lose the table row reference.

Example: link

    
21.08.2014 / 21:14