Performing Functions on a Dynamically Created Table - javascript

I am retrieving 30 bakery items from a mySQL database into a dynamic HTML table using PHP. The data retrieved are Product, Item (Primary Key), Weight, and Price. My code also creates an INPUT box, called Quantity, for each item so that the user can type in how many cases he wants. Below is a segment of the code used to generate the dynamic table:
$i=0;
while ($i < $num) {
$Item=mysql_result($result,$i,"Item");
$Product=mysql_result($result,$i,"Product");
$Weight=mysql_result($result,$i,"Weight");
$BGPrice=mysql_result($result,$i,"BGPrice");
echo "<tr>";
echo "<td>$Product</td>";
echo "<td><INPUT NAME=Item size=5 value=$Item READONLY></td>";
echo "<td><INPUT NAME=Weight size=5 value=$Weight READONLY></td>";
echo "<td><INPUT NAME=Price size=5 value=$BGPrice READONLY></td>";
echo "<td><INPUT NAME=Quantity size=5 value=0 tabindex=$i></td>";
echo "<td><INPUT NAME=ExtPrice size=5 value=0 READONLY></td>";
echo "<td><INPUT NAME=TotalWt size=5 value=0 READONLY></td>";
echo "</tr>";
$i++;
}
I need JavaScript to call a function and calculate the values for Extended Price (ExtPrice) and Total Weight (TotalWt) as soon as the user enters the number of cases he would like to order.
Here's my struggle: there are 30 items in this dynamic table and each item's INPUT NAME is the same. How can I create a function that updates ExtPrice and TotalWt for each individual product?

You could use the $i variable to uniquely identify each input
echo "<td><INPUT NAME=Item id='item$i' size=5 value='$Item' READONLY></td>";
And as a side note use quotes or double quotes to wrap $Item as it may contains spaces, etc..

Your JavaScript should not directly reference each input by name. Instead, obtain a reference to the adjacent cells in the same row.
Assuming you have a submit button that re-calculates the results, here's an example:
document.getElementById("sub").addEventListener("click", function(e) {
var i, row;
var rows = document.getElementsByTagName("tr");
// process each row individually
for (i = 0, row; row = rows[i++];) {
totalsForRow(row);
}
e.preventDefault();
}, false);
// updates the totals for each row
function totalsForRow(tr) {
var j, inp, fields = {};
var inputs = tr.getElementsByTagName("input");
if (!inputs || inputs.length === 0)
return;
// map each input by name
for (j = 0; inp = inputs[j++];) {
fields[inp.name] = inp;
}
// update totals for this row, using the stored ref to the input
fields.TotalWt.value = fields.Weight.value * fields.Quantity.value;
fields.ExtPrice.value = fields.Price.value * fields.Quantity.value;
}
This doesn't do any error checking and could be improved in several ways. It's just meant to illustrate one approach.
See a working example.

Related

How to sum up multiple Inputs multiplied by value simultaneously

So, I have This Fiddle where I have a table that has an input and a cost. It also has a bit of jquery.
$( ".total" ).change(function() {
i = 1;
var input001 = document.getElementsByName(i)[0];
var cost001 = document.getElementById("cost" + i);
var total001 = input001.value * cost001.innerHTML;
var num = total001;
var total = num.toFixed(2).replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "1,");
document.getElementById("printchatbox").value = total;
i++;
});
This code multiplies the first input times the first Item Cost. I would like to find a way to repeat this 45 times (one for each item) without copy and pasting this code 45 times... If that is the only way to do it, I can do that... but I'm hoping to learn something and make my code significantly shorter at the same time. This table is generated by php, I just copied and pasted the html that was generated for the fiddle.
while($row = $result->fetch_assoc()) {
$row['ItemID'] = ltrim($row['ItemID'], '0');
?>
<tr>
<td><input type="number" class="total" name="<?php echo $row['ItemID']?>" value "<?= isset($_POST[$row['ItemID']]) ? htmlspecialchars($_POST[$row['ItemID']]) : "" ?>"></td>
<td><?php echo $row['ItemID']?></td>
<td><?php echo $row['ItemDescription']?></td>
<td id="<?php echo 'cost' . $row['ItemID'] ?>"><?php echo $row['ItemCost']?></td>
<td id="<?php echo 'value' . $row['ItemID'] ?>"><?php echo $row['ItemValue']?></td>
</tr>
<?php
}
?>
</table>
this is the PHP code on the website that creates the table...
this is the first row of the html table.
<tbody><tr>
<td><input class="total" name="1" value="" ""="" type="number"></td>
<td>1</td>
<td>Barrel Wrap 47"x31"</td>
<td id="cost1">39.38</td>
<td id="value1">47.25</td>
</tr>
and here is an image of the first 10 rows of the table.
if I have to change something in there, that is totally fine, I'm just hoping to keep the readability and reduce the redundancy.
Thanks
Here's your updated fiddle: https://jsfiddle.net/737v3qxr/2/
So I've changed a few things:
$( ".total" ).change(function() {
var name = this.name;
var quantity = this.value;
var cost = document.getElementById("cost" + name).innerHTML;
var total = quantity * cost;
items[name] = {cost, quantity}
new_total();
});
when you apply a function/listener to something, the this references the element itself, so you didn't need to do an extra i and i++ with it.
I've also introduced JSON (it's basically a dictionary in any other language), which helps with tracking prices.
Most of the code is just renamed since your logic wasn't actually too far off, just very clumsy and convoluted.
I've also added a new_total function, which doesn't really need to be a function in and of itself, but it's just my preference.
Finally I've added an id to your total to make it easier to track.
<input id="total" type="text" readonly id="printchatbox" name="total">
There's also some weird empty text which I'm assuming refers to your php, but you will have to deal with that yourself.
<input class="total" name="45" value="" ""="" type="number">
You can use the event handler argument as well:
$( ".total" ).change(function(e) {
var cost001 = document.getElementById("cost" + e.target.name);
var total001 = e.target.valueAsNumber * Number(cost001.innerHTML);
var prev = Number(document.getElementById("printchatbox").value);
document.getElementById("printchatbox").value = total001 + prev;
});

How to store the values of an appended table row in an array variable using onchange event?

I have an ajax function that gets the values from the database and then appends those data to a table. Now, there are instances that there will be 2 or more records from the database that are being retrieved, so 2 or more table rows are also appended.My problem is, how would I able to store those values in an array variable if 2 or more values are appended on the table? Here are the codes. Thank you for the help.
$.post("{{ url('create_po') }}", { 'prod_IDs': valArray }, function(data){
var obj = JSON.parse(data);
for(var i = 0; i < obj.prodval.length; i++){
txt += "<tr class='info '><td><input type='number' class='form-control' style='width:100px;' value='0'/>"+
"</td><td>"+obj.prodval[i].unit+
"</td><td>"+obj.prodval[i].pharmaceutical+
"</td><td>"+obj.prodval[i].packaging+
"</td><td><input type='text' class='form-control' style='width:100px;' value='"+obj.prodval[i].price+"' disabled=disabled />"+
"</td><td><input type='text' class='form-control' style='width:100px;' value='0' disabled=disabled />"+
"</td></tr>";
}
$("#tbl-po-list").append(txt);
});
Table
<table id="tbl-po-list">
<tbody id="po-create"></tbody>
</table>
Bind Function to get the values onchange
$(function(){
var arrayVar = [];
$('#tbl-po-list').on( 'change keyup' , 'input[type="number"]' ,function(){
$(this).val();
$(this).parents('.info').find('.price').val();
$(this).parents('.info').find('.total').val());
});
});
I just dont know how to take a step here. How would I save the values in the array variable "arrayVar" during onchange event? What if there are 2 rows? How would I save it?
Appended rows sample image
Just store it in an object:
var data = {
qty: $(this).val(),
price: $(this).parents('.info').find('.price').val(),
total: $(this).parents('.info').find('.total').val()
}
Then when you retrieve it (based upon your image):
arrayVar[0].price // 45
arrayVar[1].price // 12

Create a submit form (wrap the table into a form and show it as a table again) from the products that were ordered

EDIT: Maybe its easier to create a new column in the database. Named: to_order.
Then create an UPDATE Query for each product . Something like : UPDATE products SET to_order = '[VALUE_INPUT]' WHERE id = '[ID_PRODUCT]'
The problem here is, where to excecute this query? How can I define the VALUE_INPUT and ID_PRODUCT for each row?
If this works, and I can UPDATE each row for that specific product etc.
I can easily create a mysqli_fetch_assoc again where only the [Product_name],[to_order] will be given.
Please help.
I'm working on a supplier order system. Where the manager of the restaurant can easily select a supplier, fill in how much stock he has now of that specific product. And it will automatically calculate how much you need to order.
This part is done.But now, once we fill in the form I want to get an overview of all products you need to order, and it needs to be printable.
For example in words explained:
We have some columns in our table [ID_product][ID_supplier][Product_name][Stock][Minimum][To_order]
ID_product, ID_supplier, Product_name and Minimum are all data from the database. Stock is what you need to fill in. And To_order is calculated by : Minimum-stock = To_order. (logic)
With a mysql_fetch_assoc command we can show all specific products with its specific id and minimum integer.
Now here is the part where my question is: Once everything is filled in, you need to click a button that refers to a next page. On this page your total input is shown, a full list.
Like: [Product_name][To_order]
So on this page you get an overview of your form where you filled in all these values. So you get a list (how big depends on how much products you have in your database) with all the calculated inputs from 'To_order'.
My problem is, if I create a Form Action into my fetch_assoc, it can read all element names, but as soon you submit the form and go to the next page. All the data is lost.
I need something where I can see the value from the previous page of that input. And then for all specific products.
My form.php (Where I need to fill in my stock in order to calculate the 'To_order' input). This is working fine.
<table width="600" border="1" cellpadding"1" cellspacing= "1" class="flatTable">
<tr class="headingTr">
<th>
Supplier code
</th>
<th>
Product
</th>
<th>
Stock
</th>
<th>
Minimum
</th>
<th>
To order
</th>
</tr>
<?php
while ($producten=mysqli_fetch_assoc($result_producten)) {
echo "<tr>";
echo "<td><form method='POST' action='lijst.php'><label name='".$producten['lev_id']."'>".$producten['lev_id']."</label></td>";
echo "<td><label name='".$producten['productnaam']."'>".$producten['productnaam']."</label></td>";
echo "<td>
<input id='".$producten['minimum']."' name='".$producten['id']."' type='text'
oninput='calculateBestelling(this.value,this.name, this.id)'
onkeypress='return event.charCode >= 48 && event.charCode <= 57'/>
</td>";
echo "<td><input id='".$producten['minimum']."' name='mytext2' type='text' readonly='true' value='".$producten['minimum']."' /></td>";
echo "<td><input id='".$producten['id']."' name='order[]' type='text' readonly='true' /></td>";
echo "</tr>";
}
?>
<script>
var minimum;
var stock;
var order;
function calculateBestelling(val,name,id){
minimum = document.getElementById(id).id;
stock = document.getElementById(id).value;
document.getElementById(name).value = minimum - val;
order = document.getElementById(name).value;
if (order < 0) {
document.getElementById(name).value = '0';
}
}
</script>
</table>
<p><input type='submit'/></p></form>
Then the next page (where the overview needs to be shown):
<header>
<h2>Complete order form - Supplier: (HERE THE SUPPLIER)</h2>
</header>
<div class="container">
<div class="row">
<table width="600" border="1" cellpadding"1" cellspacing= "1" class="flatTable">
<tr class="headingTr">
<th>
Product
</th>
<th>
To order
</th>
</tr>
<?php
//And I dont know what I need to do here. I want the values from the 3rd input the previous file. But how I can combine this with each row for a specific product?
while ($producten=mysqli_fetch_assoc($result_producten)) {
echo "<tr>";
echo "<td>PRODUCT HERE</td>";
echo "<td><input id='toorder' name='order[]' type='text' readonly='true' value='(THE VALUE OF THE PREVIOUS FILE FOR THAT PRODUCT)' /></td>";
echo "</tr>";
}
?>
</table>
</div>
</div>
I created an image, where you simple can see what I have in my mind.
URL TO IMAGE: http://i.stack.imgur.com/6AnTl.png
So we also need to check something like : if (!to_order > 0) { DONT SHOW ROW }
Feel free to change codes, maybe some other way that works? Like staying on the same page, and hide the stock and minimum values. So we only can see the ID's, Product names and To_order values?
Web pages are stateless, in other words, each request is separate to the web server. Because of this there is no link between two requests, for example form1 and form2.
In order to overcome this, you must use some form of storage that will persist across two (or more separate requests). This is called persistent storage. For long term persistent storage, use databases. For short term, use PHP sessions. You can read up on PHP sessions in the PHP manual.
To store your values from form 1, save the values into session.
In your form, you will point your form action to form1.php
form1_view.php:
<form action=<?php echo "form1.php" method="post">
<input name="field1">
<input type="form1_submit">
</form>
and your form input handler is form1.php
if (isset($_POST['form1_submit']) {
session_start();
$_SESSION['form1_inputs'] = serialize($_POST);
}
Then, when receiving the valued from form2, retrieve the values you stored from form1.
form2_view.php:
<form action=<?php echo "form2.php" method="post">
<input name="field2">
<input type="form2_submit">
</form>
Form2 is handled by its own handler.
form2.php
if (isset($_POST['form2_submit']) {
session_start();
$form1_values = unserialize($_SESSION['form1_inputs']);
$form2_values = $_POST;
// combine input from both forms into one variable.
$all_form_values = array_merge($form1_values, $form2_values)
// You can now save values from both forms. How you do this
// ...will depend on how you save the values. This is an example.
save_my_values($all_form_values);
}
After hours trying I finally figured it out.
I used $_SESSIONS to store data in. Thats one thing.
Then, made sure that the inputs are all array.
while ($producten=mysqli_fetch_assoc($result_producten)) {
echo "<form method='POST' action='verwerken.php'><tr>";
echo "<td><input name='ids[]' type='text' readonly='true' value='".$producten['id']."' /></td>";
echo "<td><input name='lev_id' type='text' readonly='true' value='".$producten['lev_id']."' /></td>";
echo "<td><input name='producten[]' type='text' readonly='true' value='".$producten['productnaam']."' /></td>";
echo "<td>
<input tabindex='1' id='".$producten['minimum']."' name='".$producten['id']."' type='text'
oninput='calculateBestelling(this.value,this.name, this.id)'
onkeypress='return event.charCode >= 48 && event.charCode <= 57'/>
</td>";
echo "<td><input id='".$producten['minimum']."' type='text' readonly='true' value='".$producten['minimum']."' /></td>";
echo "<td><input id='".$producten['id']."' name='test[]' type='text' readonly='true' /></td>";
echo "</tr>";
}
This is the while for the table.
Once you filled in all your STOCK values, it will automatically calculate the value to order.
Thats working fine. Now when you click the submit button a next page will be openend.
This page only inserts a query into a database.
For every row it will update the to_order value in the database.
$order_test = $_SESSION['hoeveelheid'] =$_POST['test'];
$ids_test = $_POST['ids'];
$producten = $_SESSION['product'] = $_POST['producten'];
foreach (array_combine($producten, $order_test) as $producten => $order_test) {
echo 'Product: ' . $producten . ' - Te bestellen: ' . $order_test.'<br>';
mysqli_query($conn, "UPDATE producten SET bestellen = '".$order_test."' WHERE productnaam ='".$producten."'");
}
$_SESSION['lev_id'] = $_POST['lev_id'];
$_SESSION['check'] = 'true';
header('Location: bestelformulier.php');
exit();
}
If the database is not that slow, you should not see this page.
After the query is done, you will be redirected to the overview page.
Bestelformulier.php.
Here you simply mysqli_fetch_assoc the values from the database again. And you have an updated form.
Thanks everyone for the help (:

Calculate the data in the every row simultaneously

I have a php code here which get the data in database and display it in php, it will create a textbox in every row and column, what I want is in every textbox that I will change in every row the last row in table should be sum up. Is there a way to do it?and how? Thank you.
<?php
include('../connect.php');
//$listsubid=$_GET['listsubid'];
$result = mysql_query("SELECT * FROM studsubject WHERE listsubid='$listsubid'");
while($row = mysql_fetch_array($result))
{
echo '<tr class="record">';
//echo '<td style="border-left: 1px solid #C1DAD7">'.$row['fname'].' '.$row['mname'].' '.$row['lname'].'</td>';
$sidnumber = $row['sidnumber'];
echo '<td><div align="left">'.$sidnumber.'&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp</div></td>';
$result1 = mysql_query("SELECT * FROM student WHERE idnumber = '$sidnumber'");
while($row1 =mysql_fetch_array($result1))
{
echo '<td><div align = "left">'.$row1['lname'].' '.$row1['fname'].' '.$row1['mname'].'</div></td>';
echo '<input type = "text" name ="grade_id[]" value = '.$row['grade_id'].'>';
$grade_id = $row['grade_id'];
$result2 = mysql_query("SELECT * FROM prelim WHERE prelim_id = '$grade_id'");
while($row2 = mysql_fetch_array($result2))
{
echo '<td><input type="text" size= "2" maxlength = "3" name="att1[]" value = '.$row2['att1'].'></td>';
echo '<td><input type="text" size= "2" maxlength = "3" name="att2[]" value = '.$row2['att2'].'></td>';
echo '<td><input type="text" size= "2" maxlength = "3" name="att3[]" value = '.$row2['att3'].'></td>';
echo '<td><input type="text" size= "2" maxlength = "3" name="att4[]" value = '.$row2['att4'].'></td>'; } ?>
Yes you can do this, but for it to happen as the user changes it you will need to use javascript.
If you want your database to update as the user makes changes, you will need to watch each input field using something like jquery. If that field changes you can then make a post request to the server. This will require you to have a place to make a post, get, or put request.
The summing will also need to be done with javascript. You will need to watch each input field. If the user makes a change to one of the fields you will need to take that value, sum it with the rest of the row and then update the total.
You can do this with php as well but it will not happen as the user inputs new values. They will need to have a submit button, and after submission the user will be presented the update view.
The best way is to use JavaScript. Is it possible to do it in PHP? Sure, but you will want to add an "Update" button that, when pressed, will not only sum the values but re-render the whole page with both the sum and the original values. I would strongly recommend not doing this, however.
If you use JavaScript, it's as simple as something like this:
var sum = document.getElementsByName("att").reduce(function(a, b) { return a + b; });
document.getElementByID('totalTextBox').value = sum;
Just use name="att" for you text boxes instead of what you have.

Adding New Row With Form Elements & A PHP Value

I have a table that when a button is pressed it adds a new row. Here it is:
<table id='editTable' width='655' border='1'>";
<tr><th width='330' align='left'>Expense Description</th><th width='100'>Cost</th></tr>
$result = mysqli_query($con,"SELECT ID,TASK_ID,EXPENSE_DESC,EXPENSE_COST FROM b_report_expense2 WHERE TASK_ID = $taskid AND REF = $referenceID");
while($row = mysqli_fetch_array($result))
{
$expenseDesc = $row['EXPENSE_DESC'];
$expenseCost = $row['EXPENSE_COST'];
$exID = $row['ID'];
<tr><td><input type='hidden' name='ref[]' value='$exID' /><input type='text' name='expense[]' value='$expenseDesc'></td>
<td><input type='text' name='expensecost[]' value='$expenseCost'></td></tr>
}
<tr><td colspan='2'><button class='no-style-button' type='button' onclick='displayResult2()'>Add Row</button><input type='submit' name='submit' value='submit'></td></tr></table>
When the add new row button is pressed it adds a new row fine however it doesn't recognise $exID as the value in the loop. Here's the javascript:
function displayResult2()
{
var table=document.getElementById("editTable");
var row=table.insertRow(1);
var cell1=row.insertCell(0);
var cell2=row.insertCell(1);
cell1.innerHTML= "<input size='5' type='hidden' name='refID' value='$referenceID' style='padding:2px;'/><input type='text' name='expenseaddition[]' style='padding:2px;' size='80'>";
cell2.innerHTML="<input type='text' name='expensecostaddition[]' style='padding:2px;' size='6'>";
}
The new row gets added to the top of the table above the other rows. Now the issue lies that $referenceID is not being recognised in the javascript. The page is declaring it that the new row is added to but it's not recognising it. This javascript is being called from an external file to the page, is this the issue?
Your help would be appreciated.
The problem is that PHP is server-side while the JS is client-side. This means that the JS gets executed after the page has been served to the user. Because PHP variables only exist on the server, the JS literally inserts $referenceID as a string.
To work around this, you could output the value of $referenceID to JS var:
<script>
var referenceID = <?php echo $referenceID?>; //If $referenceID isn't a numeric value, remember to use quotes (`'<?php echo $referenceID?>'`)
</script>
<!--Then include your JS-->
<script src="location" type="text/javascript"></script>
In that way you could get referenceID by doing:
cell1.innerHTML= "<input size='5' type='hidden' name='refID' value='"referenceID"' style='padding:2px;'/><input type='text' name='expenseaddition[]' style='padding:2px;' size='80'>";

Categories