Get data from each row.

Get data from each row.

PalmoSweetPalmoSweet Posts: 13Questions: 0Answers: 0

I try to get the dropdown info from each row. it works for every row with name but with the dropdown I only get the source code. I got this code with gave me the value of the dropdown.

console.log( $( '#select' ).find(":selected").text() );

But that code gives me the same value of one dropdown to every single row

My output in console:

Engelska 6
ENGENG06
100
A

Engelska5
ENGENG05
100
A

with this in the datatable

This is my source code:

<?php
    session_start();

    if(!isset($_SESSION["usersuid"])) {
        header("location: ../index.php");
    }

    $serverName = "localhost:3306";
    $dBUsername = "qderbntl_packageapple";
    $dBPassword = "zMWQH},bo?k]";
    $dBName = "qderbntl_db";

    $conn = mysqli_connect($serverName, $dBUsername, $dBPassword, $dBName);

    if (!$conn) {
        die("Connection failed: " . mysqli_connect_error());
    }

<?php
>
?>


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="https://cdn.datatables.net/1.12.1/css/jquery.dataTables.min.css" />
    <style>
        .material-symbols-outlined {
        font-variation-settings:
        'FILL' 0,
        'wght' 400,
        'GRAD' 0,
        'opsz' 48
        }
    </style>
    <link rel="stylesheet" href="userlobby.kurser.css">
    <link rel="stylesheet" href="https://cdn.datatables.net/v/dt/jq-3.6.0/dt-1.12.1/b-2.2.3/sl-1.4.0/datatables.min.css">
    <script src="https://code.jquery.com/jquery-3.5.1.js"></script>
    <script src="https://cdn.datatables.net/1.12.1/js/jquery.dataTables.min.js"></script>
    <script>
        $(document).ready(function () {
            var table = $('#example').DataTable();
                
        
            $('#example tbody').on('click', 'tr', function () {
                $(this).toggleClass('selected');
            });
        
            $('#button').click(function () {
                //alert(table.rows('.selected').data().length + ' row(s) selected');
                var d = (table.rows('.selected').data());
                var length = (table.rows('.selected').data().length);
                console.log(d[0][0]);
                console.log(d[0][1]);
                console.log(d[0][2]);
                //console.log( $(d[0][3]).find(":selected").text());
                console.log( $( '#select' ).find(":selected").text() );

                console.log(d[1][0]);
                console.log(d[1][1]);
                console.log(d[1][2]);
                //console.log( $(d[1][3]).find(":selected").text());
                console.log( $( '#select' ).find(":selected").text() );
                console.log(d);

                

            });

           // $('#example tbody').on( 'click', 'tr', function () {
             //   var d = table.row( this ).data();
     
                //console.log(d[0]);
                //console.log(d[1]);
                //console.log(d[2]);
                //console.log( $( d[3] ).find(":selected").val());
              //  console.log( $('#select').find(":selected").text());

            //})

        });
    </script>
</head>
<body>
    <div class="container">
        <h2>Lägg till kurser</h2>
        <button id="button">Row count</button>
        <button id="">Ändra dina kurser</button>
        <table id="example" class="display" style="width:100%;" style="height:100%;">
            <thead>
                <tr>
                    <th>Kursnamn</th>
                    <th>Kurskod</th>
                    <th>Poäng</th>
                    <th>Betyg</th>
                </tr>
            </thead>
            <tbody>
                <?php
                    if (!$conn) {
                        die("Connection failed: " . mysqli_connect_error());
                    }
                
                        $sql = "SELECT * FROM kurser";
                        $all_kurser = mysqli_query($conn, $sql);
                
                        while ($row = mysqli_fetch_array($all_kurser)) {
                            //echo "<option>" . $row['kursNamn'] . "</option>";

                            echo 
                            "<tr>
                                <td>" . $row['kursNamn'] . "</td>
                                <td>" . $row['kursKod'] . "</td>
                                <td>" . $row['kursPoints'] . "</td>
                                <td>
                                    <select id='select'>
                                        <option value='A'>
                                            A
                                        </option>
                                        <option value='B'>
                                            B
                                        </option>
                                        <option value='C'>
                                            C
                                        </option>
                                        <option value='D'>
                                            D
                                        </option>
                                        <option value='E'>
                                            E
                                        </option>
                                        <option value='F'>
                                            F
                                        </option>
                                    </select>
                                </td>
                            </tr>";
                        }
                        exit();
                ?>
            </tbody>
            <tfoot>
                <tr>
                    <th>Kursnamn</th>
                    <th>Kurskod</th>
                    <th>Poäng</th>
                    <th>Betyg</th>
                </tr>
            </tfoot>
        </table>
    </div>
</body>
</html>

How can I get the value of every row independently

sow my output in console looks like this instead
Engelska 6
ENGENG06
100
A

Engelska5
ENGENG05
100
B

Replies

  • PalmoSweetPalmoSweet Posts: 13Questions: 0Answers: 0

    I have tried this, but it does not work.

    console.log( $( d[i][3] ).find(":selected").text() );
    
  • allanallan Posts: 63,482Questions: 1Answers: 10,467 Site admin

    <select id='select'>

    This isn't valid HTML - the id attribute must be unique in the document.

    $('#example tbody').on( 'click', 'tr', function () {
      var value = $('select', this).val();
    
      console.log( value );
    });
    

    Will do it. this in that context is the tr element you clicked on and since you only have a single select in it, you can just get that element.

    Allan

  • PalmoSweetPalmoSweet Posts: 13Questions: 0Answers: 0
    edited September 2022

    Hi Allan, unfortunately, this only works with one selection. I try to take all the selected ones and get the info from each row. i do this with a for loop that looks like this. It all happens with a push of a button.

    $('#button').click(function () {
                    //alert(table.rows('.selected').data().length + ' row(s) selected');
                    var d = (table.rows('.selected').data());
                    var length = (table.rows('.selected').data().length);
                    var value = $('select', this).val();
                    /*
                    console.log(d[0][0]);
                    console.log(d[0][1]);
                    console.log(d[0][2]);
                    //console.log( $(d[0][3]).find(":selected").text());
                    console.log( $( '#select' ).find(":selected").text() );
    
                    console.log(d[1][0]);
                    console.log(d[1][1]);
                    console.log(d[1][2]);
                    //console.log( $(d[1][3]).find(":selected").text());
                    console.log( $( '#select' ).find(":selected").text() );
                    console.log(d); */
    
                    for (let i = length; i--;) {
                        console.log(d[i][0]);
                        console.log(d[i][1]);
                        console.log(d[i][2]);
                        console.log( $( '#selection1' ).find(":selected").text() );
                        console.log( value );
                    }
                    
    
                });
    

    in this, for-loop I need to specify which row the value should be taken from which I can't figure out how to do. I changed the id to something different but the same problem.

  • allanallan Posts: 63,482Questions: 1Answers: 10,467 Site admin
    table.rows({selected: true})
    

    will get you the selected rows. Then you could use rows().every() to loop over the rows - e.g.:

    table.rows({selected: true}).every(function () {
      console.log( $('select', this.node()).val() );
    });
    

    Allan

  • PalmoSweetPalmoSweet Posts: 13Questions: 0Answers: 0

    It works if you want to itarate thru all of them. This is what i try to do. I select the rows i want and i get every signle one of the option in the select elemnt and console.log them in different objects. This is how it looks when i use d[i][3] i = the row.

    Engelska5
    ENGENG05
    100
    <select id="selection1">
    <option value="A">A</option>
    <option value="B">B</option>
    <option value="C">C</option>
    <option value="D">D</option>
    <option value="E">E</option>
    <option value="F">F</option>
    </select>

    And this is how i want it to look like

    Engelska5
    ENGENG05
    100
    A (of i choose antother one that one should be here)

    I do this by looping thru every object in the array but with d[i][3] i get the source code and none of your tips include a parameter of which row it should be applied on which is a cruel part of the syntax that i need. i hope my question got more clear now.

    The problme with your last code is that it returnes all the rows without giving it any place like it should in the for loop

  • allanallan Posts: 63,482Questions: 1Answers: 10,467 Site admin

    I'm afraid I'm just under understanding what you are trying to do. If you need the rest of the data from the row use row().data():

    table.rows({selected: true}).every(function () {
      var data = row.data();
    
      console.log(data[0]);
      console.log(data[1]);
      console.log(data[2]);
      console.log( $('select', this.node()).val() );
    });
    

    Allan

  • kthorngrenkthorngren Posts: 21,315Questions: 26Answers: 4,948

    If you want to access the HTML element of a cell use row().node() or maybe better is cell().node(). I built a simple test case based on your example table data.
    http://live.datatables.net/cavawiqu/1/edit

    It uses rows().every() with the selector-modifier of {selected: true}, like Allan suggested. In the loop it uses cells().every() to loop all the cells in the row. If the column contains the select list then it uses cell().node() to get the HTML from the cell. Otherwise it uses cell().data() to get the cell's data.

    Is this what you are looking for?

    Kevin

  • PalmoSweetPalmoSweet Posts: 13Questions: 0Answers: 0

    Hi Kevin, your example helped me solve it, i just changed the {selected: true} to my ".selceted" class and it is now working exactly how i wanted it to. Thanks alot!

  • PalmoSweetPalmoSweet Posts: 13Questions: 0Answers: 0

    But i have one more ask, is it possile to get these in to a array variable?

    // Skriver ut all info i konsolen
                        table.rows('.selected').every( function (rowIdx, tableLoop, rowLoop ) {
                            table.cells( $(this), $('td') ).every( function ( rowIdx, colIdx ) {
                                if(colIdx === 3 ) {
                                    var node = this.node();
                                    console.log( $('select', node).val() );
                                } else {
                                    var data = this.data();
                                    console.log(data);
                                }
                            })
                        })
    
    

    so insted of printing it out in console put i inside a varible and then only print once in the console? i need to loop thrue the array to send the info via mysql

  • kthorngrenkthorngren Posts: 21,315Questions: 26Answers: 4,948

    You should be able to with Allan's last example. The data variable is an array. You can just replace data[3] with the select value like this:

    data[3] = $('select', this.node()).val();
    

    Kevin

  • PalmoSweetPalmoSweet Posts: 13Questions: 0Answers: 0

    Hi Kevin, Unfirtantly i only get undefined from that. This is the code and instead of console.log I would like to store every single value in a big array and then log it as one piece once. is that possible?

    table.rows('.selected').every( function (rowIdx, tableLoop, rowLoop ) {
                            table.cells( $(this), $('td') ).every( function ( rowIdx, colIdx ) {
                                if(colIdx === 3 ) {
                                    var node = this.node();
                                    //info[1] = ( $('select', node).val() );
                                    console.log( $('select', node).val() );
                                } else {
                                    var data = this.data();
                                    console.log(data);
                                }
                            })
                            //console.log(info[1]);
                        })
    
  • kthorngrenkthorngren Posts: 21,315Questions: 26Answers: 4,948

    i only get undefined from that.

    Right, there is a type in the code. Instead of var data = row.data(); it should be var data = this.data();. Changing row, which is undefined, to this. Here is the updated example building an array of the selected rows.
    http://live.datatables.net/mahuweme/1/edit

    Kevin

  • PalmoSweetPalmoSweet Posts: 13Questions: 0Answers: 0

    Kevin you are a hero, my problem is now solved thank you alot :smile:

Sign In or Register to comment.