How to get a javascript function working inside a php table? - javascript

I am trying to get the Multiply function to run and multiply the Order Quantity times the item price. I cannot get the function to run inside the PHP loop using the oninput attribute.
<script type="text/javascript">
function Multiply() {
var myBox1 = document.getElementById('editedvalues[]').value;
var myBox2 = document.getElementById('price').value;
var result = document.getElementById('result');
var myResult = myBox1 * myBox2;
result.value = myResult;
}
</script>
<?php
$sql = "SELECT item_price.item_id,
item_price.ITEM_NAME,
suggested_qty,
Price_item
FROM item_price
JOIN suggested_item ON item_price.ITEM_NAME = suggested_item.ITEM_NAME";
$result = $conn->query($sql);
?>
form action="#" method="post">
<tr>
<th> ID</th>
<th>Item Name</th>
<th>Suggested Quantity</th>
<th>Price</th>
<th>OrderQuanity</th>
<th>Total Cost</th>
</tr>
<?php
while ($row = $result->fetch_assoc())
{
echo "<tr>";
echo "<td>{$row['item_id']}</td>";
echo "<td>{$row['ITEM_NAME']}</td>";
echo "<td>{$row['suggested_qty']}</td>";
echo "<td>{$row['Price_item']}</td>";
echo "<td><input type='text' name='editedvalues[]' value='{$row['suggested_qty']}' oninput='Multiply()' /></td>";
echo "<td><input name='result' /></td>";
echo "</tr>";
}
?>

You're using the document.getElementById function to refer to elements, but in addition to the fact that there are multiple inputs that this function can run on, your inputs don't even have an ID.
To make sure this function works on the input in question, you'll need to look at the target of the event instead of ignoring it. As well, you should use proper event binding instead of inline oninput attributes.
You also weren't using a table element, and you should really break out of PHP for huge blocks of HTML code.
This would be much easier using some framework like jQuery, but this should work.
var nodes = document.getElementsByClassName("qtyinput");
for (var i = 0; i < nodes.length; i++) {
nodes[i].addEventListener('input', multiply, false);
}
function multiply(e) {
var qty = e.target.value;
var price = e.target.parentNode.parentNode.getElementsByClassName("pricetd")[0].textContent;
var result = e.target.parentNode.parentNode.getElementsByClassName("resultinput")[0];
var myResult = qty * price;
result.value = myResult;
}
<?php
$sql = "SELECT item_price.item_id,
item_price.ITEM_NAME,
suggested_qty,
Price_item
FROM item_price
JOIN suggested_item ON item_price.ITEM_NAME = suggested_item.ITEM_NAME";
$result = $conn->query($sql);
?>
<form action="#" method="post">
<table>
<tr>
<th> ID</th>
<th>Item Name</th>
<th>Suggested Quantity</th>
<th>Price</th>
<th>OrderQuanity</th>
<th>Total Cost</th>
</tr>
<!-- test data for snippet -->
<tr>
<td>111</td>
<td>Test item</td>
<td>4</td>
<td class="pricetd">40</td>
<td>
<input type="text" name="editedvalues[]" class="qtyinput" value="4" />
</td>
<td><input name='result' class="resultinput" /></td>
</tr>
<?php while ($row = $result->fetch_assoc()) :?>
<tr>
<td><?=$row["item_id"]?></td>
<td><?=$row["ITEM_NAME"]?></td>
<td><?=$row["suggested_qty"]?></td>
<td class="pricetd"><?=$row["Price_item"]?></td>
<td>
<input type="text" name="editedvalues[]" class="qtyinput" value="<?=$row["suggested_qty"]?>" />
</td>
<td><input name='result' class="resultinput" /></td>
</tr>
<?php endwhile?>
</table>
<form>

Related

calculation of two input field into third input field having multiple table rows in jquery

I am doing calculation in the third input field based on the value filled in the two input field. And here I have multiple row. Each row calculation should be done separately so i am using each function. But the calculation is not working.
I am new in Jquery so where code is getting wrong??
<table>
<tr>
<th><?= __('Quantity Offered')?></th>
<th><?= __('Offer Price')?></th>
<th><?= __('Total Offer Price')?></th>
</tr>
<tr class="productNRow">
<td><?php echo $this->Form->input("supplier_offer_products.0.qty_offered",['id'=>'qtyOffered']);?></td>
<td><?php echo $this->Form->input("supplier_offer_products.0.offer_price",['id'=>'priceOffered']);?></td>
</tr>
<tr class="productNRow">
<td><?php echo $this->Form->input("supplier_offer_products.1.qty_offered",['id'=>'qtyOffered']);?></td>
<td><?php echo $this->Form->input("supplier_offer_products.1.offer_price",['id'=>'priceOffered']);?></td>
</tr>
</table>
<script>
$(document).ready(function(){
$(".productNRow").each(function(){
var sentRec = $(this);
var total;
$(this).find("#qtyOffered").on('change', function () {
var qty = $(sentRec).find("#qtyOffered").val();
var offer = $(sentRec).find("#priceOffered").val();
var total = qty * offer;
$('#totalOrder').val(total);
});
});
});
You cannot have multiple IDs. Use classes and add the missing #totalOrder elements.
The jQuery and PHP than could look like this:
jQuery(function( $ ) {
$(".productNRow").each(function() {
var $row = $(this);
var $qty = $row.find(".qtyOffered"); // use classes! (see PHP too)
var $prc = $row.find(".priceOffered");
var $tot = $row.find(".totalOrder");
$qty.on('input', function() {
var qty = $(this).val();
var offer = $prc.val();
var total = qty * offer;
$tot.val(total);
});
});
});
<table>
<tr>
<th>Quantity Offered</th>
<th>Offer Price</th>
<th>Total Offer Price</th>
</tr>
<tr class="productNRow">
<td>
<?php echo $this->Form->input("supplier_offer_products.0.qty_offered",['class'=>'qtyOffered']);?>
</td>
<td>
<?php echo $this->Form->input("supplier_offer_products.0.offer_price",['class'=>'priceOffered']);?>
</td>
<td>
<input class="totalOrder">
</td>
</tr>
<tr class="productNRow">
<td>
<?php echo $this->Form->input("supplier_offer_products.1.qty_offered",['class'=>'qtyOffered']);?>
</td>
<td>
<?php echo $this->Form->input("supplier_offer_products.1.offer_price",['class'=>'priceOffered']);?>
</td>
<td>
<input class="totalOrder">
</td>
</tr>
</table>
or going the other way around (input→parent→inputs) without using the .each() method
jQuery(function( $ ) {
$(".qtyOffered").on('input', function() {
var $row = $(this).closest(".productNRow");
var $prc = $row.find(".priceOffered");
var $tot = $row.find(".totalOrder");
var qty = $(this).val();
var offer = $prc.val();
var total = qty * offer;
$tot.val(total);
});
});

Clicking the row of the table and displaying it to text field

I have text field inside the table, and also the data below in it..I want to display the data to text field after clicking the row.
I tried these code but nothing happens. Help me please.
These are the code for the table.
<table id="tableqwe">
<tr>
<th>Name</th>
<th>Id Number</th>
<th>Course</th>
<th>Year level</th>
<th>School Year</th>
<th>Semester</th>
<th></th>
</tr>
<tr>
<th><input type="Text" id="name1" name="name1" style="width:200px;"></th>
<th><input type="Text" id="idnumber2" name="idnumber2" style="width:200px;"></th>
<th><input type="Text" id="course3" name="course3" style="width:80px;"></th>
<th><input type="Text" id="yearlvl4" name="yearlvl4" style="width:200px;"></th>
<th><input type="Text" id="schoolyear5" name="schoolyear5" style="width:150px;"></th>
<th><input type="Text" id="semester6" name="semester6" style="width:100px;"></th>
<th><input type="button" value="Add" class="btntable edit" style="width:50px;"></th>
</tr>
<?php
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['name'] . "</td>";
echo "<td>" . $row['Id_number'] . "</td>";
echo "<td>" . $row['course'] . "</td>";
echo "<td>" . $row['year_level'] . "</td>";
echo "<td>" . $row['school_year'] . "</td>";
echo "<td>" . $row['semester'] . "</td>";
echo "<td>"?><input type="button" class="btntable delete" value="Delete" style="width:50px;"><?php
echo "</tr>";
}
?>
</table>
And these are the javascript code...
<script>
var table1 = document.getElementById('tableqwe');
for(var i = 2; i < table1.rows.length; i++)
{
table.rows[i].onclick = function()
{
rIndex = this.rowIndex;
console.log(rIndex);
document.getElementsByName("name1").value = this.cells[0].innerHTML;
document.getElementsByName("idnumber2").value = this.cells[1].innerHTML;
document.getElementsByName("course3").value = this.cells[2].innerHTML;
document.getElementsByName("yearlvl4").value = this.cells[3].innerHTML;
document.getElementsByName("schoolyear5").value = this.cells[4].innerHTML;
document.getElementsByName("semester6").value = this.cells[5].innerHTML;
}
}
</script>
Can someone help me with this.! All I want is if I click any row of the table, it will directly display it to the text field.
You should use HTML DOM getElementById() Method to get the element with the specified ID.
HTML DOM getElementsByName() Method Get all elements with the specified name.
You have to edit your js script as follows.
If you are using 'HTML DOM getElementsByName() Method' to assign value to that specific element you should use it as document.getElementsByName("name1")[0].value="value". Since this method returns the collection of objects having the same name passed as it's parameter.
If you are using the HTML DOM getElementById() you can assign values into it by using the code as document.getElementById("idofelement").value="value".
An example is given in the snippet below.
var table1 = document.getElementById('tableqwe');
for(var i = 2; i < table1.rows.length; i++)
{
table1.rows[i].onclick = function()
{
rIndex = this.rowIndex;
console.log(this.cells[0].innerHTML);
document.getElementById("name1").value = this.cells[0].innerHTML;
console.log(document.getElementsByName("name1")[0].value);
document.getElementById("idnumber2").value = this.cells[1].innerHTML;
document.getElementById("course3").value = this.cells[2].innerHTML;
document.getElementById("yearlvl4").value = this.cells[3].innerHTML;
document.getElementById("schoolyear5").value = this.cells[4].innerHTML;
document.getElementById("semester6").value = this.cells[5].innerHTML;
}
}
<table id="tableqwe">
<tr>
<th>Name</th>
<th>Id Number</th>
<th>Course</th>
<th>Year level</th>
<th>School Year</th>
<th>Semester</th>
<th></th>
</tr>
<tr>
<th><input type="Text" id="name1" name="name1" style="width:200px;"></th>
<th><input type="Text" id="idnumber2" name="idnumber2" style="width:200px;"></th>
<th><input type="Text" id="course3" name="course3" style="width:80px;"></th>
<th><input type="Text" id="yearlvl4" name="yearlvl4" style="width:200px;"></th>
<th><input type="Text" id="schoolyear5" name="schoolyear5" style="width:150px;"></th>
<th><input type="Text" id="semester6" name="semester6" style="width:100px;"></th>
<th><input type="button" value="Add" class="btntable edit" style="width:50px;"></th>
</tr>
<tr>
<td>name</td>
<td>12</td>
<td>Course</td>
<td>Course 12</td>
<td>School year 12</td>
<td>School year 12</td>
<td><input type="button" class="btntable delete" value="Delete" style="width:50px;"></tr>;
</table>
Change the code like this.
<?php
while($row = mysqli_fetch_array($result)) {
echo "<tr contenteditable = 'true' id='name' data-name= '//php variable like $id '>";
echo "<td>" . $row['name'] . "</td>";
echo "<td>"?><input type="button" class="btntable delete" value="Delete" style="width:50px;"><?php
echo "</tr>";
}
?>
then change your javascript to like this (Im coding it Jquery and change it you want.)
<Script>
$(document).on('click', '#button Id or Class here', function(){
//get id of user updates
var id = $(this).data("name");
// get values
var val = $(this).text();
});
</script>
this the solution. if is this help for your leave a comment.

scroll through the records in a table with php Javascript

I have a table in html with data printed via php (mysql). I wish that by pressing a button next to each record, I appear the value of the associated record and print the displayed value.
I nearly succeeded but every time I press takes me only the first record button and not that of the same row.
<?php
$data = 'sito';
$db = mysqli_connect('localhost', 'root', '', $data);
$result= mysqli_query ($db, "SELECT * FROM prodotti");
echo"<table id='tabella' width='800' border='1'>";
echo"<tr>
<th >Codice</th>
<th >Nome</th>
<th >Giacenza</th>
<th> Azioni </th>
<th >Data consegna</th>
</tr>";
while($row=mysqli_fetch_array($result)){
echo"<tr>
<td id='cod'>".$row['Codice']."</td>
<td id='nom'>".$row['Nome']."</td>
<td id='gia'>".$row['Giacenza']."</td>
<td id='dat'>
<button id='pulsante' onClick='giacenza()'>pulsante</button>
</td>
<td id='datac'>";
$dat=$row['Data consegna'];
$data=substr($dat,8,2)."-".substr($dat,5,2)."-".substr($dat,0,4);
echo $data."</td>
</tr>";}
echo"</table>";
?>
here php code
sorry
var d = document.createElement("div");
d.setAttribute("id", "modifica");
var String = "<textarea id='textarea' rows='1' cols='3'></textarea> <input type='text' id='input'></input> <button type='submit' id = 'boton'>aggiorna </button>";
d.innerHTML = String;
var g = document.getElementById("gia").textContent;
document.body.appendChild(d);
document.getElementById("textarea").innerHTML = g;
I would suggest pass the value to the function as a parameter
PHP Code
<?php
$data = 'sito';
$db = mysqli_connect('localhost', 'root', '', $data);
$result= mysqli_query ($db, "SELECT * FROM prodotti");
echo"<table id='tabella' width='800' border='1'>";
echo"<tr>
<th >Codice</th>
<th >Nome</th>
<th >Giacenza</th>
<th> Azioni </th>
<th >Data consegna</th>
</tr>";
while($row=mysqli_fetch_array($result)){
echo"<tr>
<td id='cod'>".$row['Codice']."</td>
<td id='nom'>".$row['Nome']."</td>
<td id='gia'>".$row['Giacenza']."</td>
<td id='dat'>
<!-- Next line has the change -->
<button id='pulsante' onClick='giacenza(/"".$row['Giacenza']."/")'>pulsante</button>
</td>
<td id='datac'>";
$dat=$row['Data consegna'];
$data=substr($dat,8,2)."-".substr($dat,5,2)."-".substr($dat,0,4);
echo $data."</td>
</tr>";
}
echo"</table>";
?>
And your javascript code:
Instead of taking value from element it uses the value from passed parameter
function giacenza(g){
var d = document.createElement("div");
d.setAttribute("id", "modifica");
var String = "<textarea id='textarea' rows='1' cols='3'></textarea> <input type='text' id='input'></input> <button type='submit' id = 'boton'>aggiorna </button>";
d.innerHTML = String;
document.body.appendChild(d);
document.getElementById("textarea").innerHTML = g;
}
The buttons that you are putting next to each record are all the same. You are not giving your JavaScript any way of knowing which button was pressed. try something like this:
<button id='pulsante' onClick='giacenza(".$row['Codice'].")'>pulsante</button>
and change your giacenza javascript function to take Codice as a parameter and use it to identify which record is being manipulated.
I assume Codice is your item code or something unique to the record. If you don't have a field like that you need to come up with something.
You also need unique identifiers for anything else like the text boxes you are manipulating. Instead of using id of "MyBox" use id of "MyBox_".$row['Codice']

HTML form doesn't capture all the checkboxes from Bootstrap responsive table

I have a table which displays results from my DB. In the last column I have checkboxes and by clicking submit button I am sending an array of account_id's to another php file. Everything works fine but the problem is that I am using a Bootstrap responsive table which can show 10-100 results on each page and the form only captures results on the current page. If I check boxes on different pages and switch between them, they still remain checked, though.
Here is my HTML:
<form action="compare.php" method="post">
<table class="table table-hover" id="dataTables-example">
<thead>
<tr>
<th style="text-align:center;">Account name</th>
<th style="text-align:center;">Address</th>
<th style="text-align:center;">Phone number</th>
<th style="text-align:center;">Website</th>
<th style="text-align:center;">Compare</th>
</tr>
</thead>
<tbody>
<?php
$result= mysql_query("select * from accounts order by account_name ASC" ) or die (mysql_error());
while ($row= mysql_fetch_array ($result) ){
?>
<tr>
<td class='clickable-row' data-href="select.php?id=<?php echo $row ['account_id'];?>"> <?php echo $row ['account_name'];?></td>
<td class='clickable-row' data-href="select.php?id=<?php echo $row ['account_id'];?>"> <?php echo $row ['address']; ?></td>
<td class='clickable-row' data-href="select.php?id=<?php echo $row ['account_id'];?>"> <?php echo $row ['phone_number']; ?></td>
<td class='clickable-row' data-href="select.php?id=<?php echo $row ['account_id'];?>"> <?php echo $row ['website']; ?></td>
<td> <input type="checkbox" name="checkboxvar[]" value="<?php echo $row ['account_id'];?>" /></td>
</tr>
<?php } ?>
</tbody>
</table>
<input class="btn btn-success" type="submit" value="Compare" id="submit">
</form>
I tried to use jQuery to see if it can capture the checkboxes from the whole table, but results is the same as trying an HTML form.
This script is supposed to capture them and make an alert:
<button id="bt1">Get</button>
<script>
$('#bt1').on('click', function () {
//Get checked checkboxes
var checkedCheckboxes = $("#dataTables-example :checkbox:checked"),
arr = [];
//For each checkbox
for (var i = 0; i < checkedCheckboxes.length; i++) {
//Get checkbox
var checkbox = $(checkedCheckboxes[i]);
//Get checkbox value
var checkboxValue = checkbox.val();
//Get siblings
var siblings = checkbox.parent().siblings();
//Get values of siblings
var value1 = $(siblings[0]).text();
var value2 = $(siblings[1]).text();
arr.push(checkboxValue + '-' + value1 + '/' + value2);
alert(checkboxValue + '-' + value1 + '/' + value2);
}
});
</script>
Is there a way to do it?
You can use Datatables object:
$('input', oTable.fnGetNodes()).each(function () {
if($(this).is('checked')){
console.log($(this).val());
}
});
Solved!
Include this script:
<script type="text/javascript" src="//cdn.datatables.net/plug-ins/f2c75b7247b/api/fnGetHiddenNodes.js"></script>
And this paste this function:
<script>
$(document).ready(function() {
oTable = $('#yourTableID').dataTable();
$('form').submit(function(){
$(oTable.fnGetHiddenNodes()).find('input:checked').appendTo(this);
});
});
</script>
All checkboxes are captured by clicking submit button.

Switch case (JavaScript) inside a while loop (PHP)

I have this JavaScript code, it works well, but when I tried to customize some math operations based on $id_math, it reads only the first row of the array inside the while loop, so calculate all the rows using the same $id_math, What changes do I need to do in my code, to get individual $id_math for every single row and perform the corresponding operation?.
$id_math is a php variable I use to store the value I got from my database.
example: $id_math = 11, $operation_name = addition.
Here is my example.
Script
$(function(){
CalculateTotal();
// Adding the change events for the Price and
// quantity fields only..
// Changing the total should not affect anything
$('.quantity , .price').on('change', function() {
UpdateTotals(this);
});
});
function UpdateTotals(elem) {
// This will give the tr of the Element Which was changed
//in my code I have it like this
var abc=<?php echo id_math ?>;
var $container = $(elem).parent().parent();
var quantity = $container.find('.quantity').val();
var price = $container.find('.price').val();
var subtotal = parseFloat(quantity) + parseFloat(price);
var subtotalmultiplication = parseFloat(quantity) * parseFloat(price);
var subtotaldivision = parseFloat(quantity) / parseFloat(price);
switch (abc) {
case 12:
$container.find('.subtotal').text(subtotal.toFixed(2));
$container.find('.txtresult').val(subtotal.toFixed(2));
break;
case 11:
$container.find('.subtotal').text(subtotalmultiplication.toFixed(2));
$container.find('.txtresult').val(subtotalmultiplication.toFixed(2));
break;
case 13:
$container.find('.subtotal').text(subtotaldivision.toFixed(2));
$container.find('.txtresult').val(subtotaldivision.toFixed(2));
break;
}
//document.getElementById("txtresult").value = subtotal.toFixed(2);
}
function CalculateTotal(){
// This will Itearate thru the subtotals and
// claculate the grandTotal and Quantity here
var lineTotals = $('.subtotal');
var quantityTotal = $('.quantity');
var grandTotal = 0.0;
var totalQuantity = 0;
$.each(lineTotals, function(i){
grandTotal += parseFloat($(lineTotals[i]).text()) ;
totalQuantity += parseFloat($(quantityTotal[i]).val())
});
$('.totalquantity').text(totalQuantity);
$('.grandtotal').text(parseFloat(grandTotal ).toFixed(2) );
}
php code
<table id="tabla-registros" class="table table-striped table-bordered bootstrap-datatable datatable responsive">
<thead>
<tr>
<th>Nº Reg</th>
<th>Fecha</th>
<th>Nombre Completo del Paciente</th>
<th>Clave para la Descarga</th>
<th>Estado del Registro</th>
<th>Acciones</th>
</tr>
</thead>
<tbody>
<?php
$numrows = mysql_num_rows($list_results);
if($numrows > 0){
while($row=mysql_fetch_array($list_results)){
$patient_name= utf8_encode($row['nombrepaciente']);
$keyword= $row['llave'];
$url_result= $row['resultado'];
$comments= $row['observaciones'];
$status_result= $row['nombre_estado'];
$date_result= $row['fecha'];
$id_status= $row['idestado'];
$id_resultado= $row['idresultados'];
$id_math = $row['idmath'];
?>
<tr>
<td><?php echo $id_resultado;?></td>
<td><?php echo $date_result;?></td>
<td><?php echo $patient_name;?></td>
<td><?php echo $keyword;?></td>
<?php switch($id_status){
case '3':?>
<td><span class="label-success label label-default"><?php echo $status_result; ?></span></td>
<?php break; ?>
<?php case '1':?>
<td> <span class="label-warning label label-default"><?php echo $status_result; ?></span></td>
<?php break;?>
<?php case '2':?>
<td> <span class="label-default label label-danger"><?php echo $status_result; ?></span></td>
<?php break; }?>
<!--This is the block of the code where I need help because the javascript code only reads the first row of the while loop to perform the operation, but the second row has another id_math to calculate other operations -->
<table>
<tr>
<th width=200px>Description</th>
<th width=60px>DATA1</th>
<th width=60px>DATA2</th>
<th width=60px>Total</th>
</tr>
<tr>
<td width=200px>CALCULATE</td>
<td width=60px><input type="text" value="15.99" class="price" /></td>
<td width=60px><input type="text" value="1" class="quantity" /></td>
<td width=60px><input type="text" value="" name="txtresult" id= "txtresult" class="txtresult" /></td>
</tr>
</table>

Categories