user3651819 user3651819 - 5 months ago 12
Javascript Question

Javascript pick values only from first row in the table

I am printing results from a database in to a table. Then I need to use them up and I use javascript.
I also use PHP to retrieve values from the database and print them in the table.

<table id="datatable" class="table table-bordered" style="width: 100%;">
<thead>
<tr class="bg-teal-300">
<th>Br.</th>
<th>Materijal</th>
<th>Tezina</th>
<th>Boja</th>
<th>Količina </th>
<th><center><i class="ion-ios-cart-outline" style="font-size:18px; color:white;"><center></th>
</tr>
</thead>
<tbody>
<?php while($r=$q->fetch()){
$id_print = $r['Id'];
?>
<tr>
<td><?='R-'. $r['Id']?></td>
<td><?=$r['Material']?> </td>
<td><?=$r['Quantity']?></td>
<td><?=$r['Color']?></td>
<td><input type="text" class="form-control" id="quantity" placeholder="" ></td>
<td><center><button type="button" id="item" class="btn btn-default btn-sm" onclick="myFunction()" value="<?php echo 'R-' . $id_print ;?>"> <i class="icon-cart"></i></button></center></td>
</tr>
<?php } ?>
</tbody>
</table>


After printing the results in the table, I need to get two values after clicking on a button.
I need to get those values from an input field (last column) user type number, and then click on that button.
For that I am using the following javascript

<script>
function myFunction() {
var x = document.getElementById("quantity").value;
var y = document.getElementById("item").value;

window.location.href = "materijali.php?w1=" + x + "&w2=" + y
}
</script>


By using the script above, I always get the values from the first row and redirect those values to the URL.
I was wondering how to get values from the row where button is clicked.

Answer

Just make few changes,

<table id="datatable" class="table table-bordered" style="width: 100%;">
<thead>
    <tr class="bg-teal-300">
        <th>Br.</th>
        <th>Materijal</th>
        <th>Tezina</th>
        <th>Boja</th>
        <th>Količina </th>
        <th><center><i class="ion-ios-cart-outline" style="font-size:18px; color:white;"><center></th>
    </tr>
</thead>
<tbody>
    <?php while($r=$q->fetch()){ 
        $id_print = $r['Id'];
        ?>
    <tr>
        <td><?='R-'. $r['Id']?></td>
        <td><?=$r['Material']?> </td>
        <td><?=$r['Quantity']?></td>
        <td><?=$r['Color']?></td>
        <td><input type="text" class="form-control" id="quantity" placeholder="" ></td>
        <td><center><button type="button" id="item" class="btn btn-default btn-sm" onclick="myFunction(this)" value="<?php echo 'R-' . $id_print ;?>"> <i class="icon-cart"></i></button></center></td> 
    </tr>
    <?php } ?>
</tbody>

And in javascript:

<script>
function myFunction(object) {
var x = $(object).attr("value"); 
var y = $('#quantity', $(object).parent().parent().siblings()).val(); 
window.location.href = "materijali.php?w1=" + x + "&w2=" + y; 
}
</script>

Hope this will help!