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'>";
Related
I have a table with 3 text fields
i want to add the same text fields on clicking check box i have the following code
how can i do it with php and javascript
echo "<td>Screen ".$i."</td>";
echo "<td><input type='text' id='filmname".$k."' name='filmname".$k."'value='".$prefilm."'></td>";
echo "<td><input type='text' id='Language".$k."' name='Language".$k."'value='".$prelang."'></td>";
echo "<td><input type='text' id='showtime".$k."' name='showtime".$k."'value='".$prescreen."'></td>";
echo "<td ><input type='checkbox' class='Checkbox' id='addshow".$k."' autocomplete='off'
name='addshow".$k."' value='addshow' onclick='addshow(".$k.")</td>";
It would be great if you can clarify where you want to add which text fields when the checkbox got checked.
Two ideas:
You can create your text fields at the same time when you create your table and then hide/show them with CSS and JavaScript. (Preferred)
Add a click listener to your checkbox and create your text fields dynamically with JS with document.createElement('input') Learn more here
Code examaple for the 2nd option:
const check = document.querySelector('input[type=checkbox]');
check.addEventListener('click', createTextInput);
function createTextInput() {
const target = document.querySelector(YOUR TARGET SELECTOR);
const input = document.createElement('input');
input.setAttribute('type', 'text');
input.addEventListener(OPTIONAL IF YOU WANT)
target.appendChild(input); // this adds the new input into your target
}
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 (:
Evening,
I'm kinda stuck here. I've made a login for our employees to easily create new invoice (it's in danish though, sorry) and almost everything is completed. But one thing I can't figure out how to do, is to delete a material (materiale in danish) from a while loop. I've got a form with a while loop within it, which displays all of the materials, and right next to the material input fields I've created a small a href link, which should delete the field with some help from javascript. It deletes the field perfectly, but doesn't delete the data from our mysql database. So every time I refresh the page, then the data are back. Updating and inserting isn't a problem. The code looks like this:
$ct_update = 0;
foreach ($_POST['beskrivelse_update'] as $k => $value) {
$beskrivelse_update = addslashes($value);
$enhed_update = addslashes($_POST['enhed_update'][$ct_update]);
$stk_update = addslashes($_POST['stk_update'][$ct_update]);
$vejl_eks_moms_update = addslashes($_POST['vejl_eks_moms_update'][$ct_update]);
$update_id = (int)$_POST['update_id'][$ct_update];
$db->query("UPDATE faktura_materialer SET beskrivelse = '$beskrivelse_update', enhed = '$enhed_update', stk = '$stk_update', vejl_eks_moms = '$vejl_eks_moms_update', subtotal = '$stk_update' * '$vejl_eks_moms_update' WHERE id = '$update_id' LIMIT 1");
$ct_update++;
}
$ct_ny = 0;
if(isset($_POST['beskrivelse_ny'])){
foreach ($_POST['beskrivelse_ny'] as $k => $value) {
$beskrivelse_ny = addslashes($value);
$enhed_ny = addslashes($_POST['enhed_ny'][$ct_ny]);
$stk_ny = addslashes($_POST['stk_ny'][$ct_ny]);
$vejl_eks_moms_ny = addslashes($_POST['vejl_eks_moms_ny'][$ct_ny]);
$db->query("INSERT INTO faktura_materialer (faktura_id, beskrivelse, enhed, stk, vejl_eks_moms, subtotal) VALUES ('".$_faktura->faktura_id."', '".$beskrivelse_ny."', '".$enhed_ny."', '".$stk_ny."', '".$vejl_eks_moms_ny."', '".$stk_ny."' * '".$vejl_eks_moms_ny."')");
$ct_ny++;
}
}
Hopefully you understand what I want to do, otherwise just comment. Have a nice evening peeps :)
Edit:
I want the delete query to be submitted when the user clicks the submit button "Save changes". This is my javascript code:
<script type="text/javascript">
function myFunction()
{
var table = document.getElementById("produkter_rows");
var row = table.insertRow(-1);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
var cell4 = row.insertCell(3);
var cell5 = row.insertCell(4);
cell1.innerHTML = '<td><input style="width:450px;" class="text-input" type="text" name="beskrivelse_ny[]" value=""></td>';
cell2.innerHTML = '<td><input style="width:60px;" class="text-input" type="text" name="enhed_ny[]" value=""></td>';
cell3.innerHTML = '<td><input style="width:30px;" class="text-input" type="text" name="stk_ny[]" value=""></td>';
cell4.innerHTML = '<td><input style="width:205px;" class="text-input" type="text" name="vejl_eks_moms_ny[]" value=""></td>';
cell5.innerHTML = '<td><img src="images/icons/slet.gif" width="16" alt="Slet" /></td>';
}
removeRow = function(el) {
$(el).parents("tr").remove()
}
</script>
When the user clicks the delete icon right next to the material, then it will be deleted. And it does delete the input fields, but not from the database in mysql.
Second edit:
This is HTML and PHP for updating current data in MySQL database:
$materialer_query = $db->query("SELECT faktura_materialer.id as materialer_id, faktura.*, faktura_materialer.* FROM faktura, faktura_materialer WHERE faktura_materialer.faktura_id = faktura.id");
while($mat = $materialer_query->fetch_object()){
?>
<tr>
<input type="hidden" name="update_id[]" value="<? print $mat->id; ?>" />
<td><input style="width:450px;" class="text-input" type="text" name="beskrivelse_update[]" value="<? print $mat->beskrivelse; ?>"></td>
<td><input style="width:60px;" class="text-input" type="text" name="enhed_update[]" value="<? print $mat->enhed; ?>"></td>
<td><input style="width:30px;" class="text-input" type="text" name="stk_update[]" value="<? print $mat->stk; ?>"></td>
<td><input style="width:205px;" class="text-input" type="text" name="vejl_eks_moms_update[]" value="<? print $mat->vejl_eks_moms; ?>"></td>
<td></td>
<td><img src="images/icons/slet.gif" width="16" alt="Slet" /></td>
</tr>
<?
}
The hidden input field name="update_id[]" is added to the form when I am updating. I hope this helps...
You need to inform the PHP script that you wish to delete the record. One solution would be to use a hidden input which is set when you call removeRow, e.g.
function removeRow(el) {
// get the table row
var row = $(el).parents('tr:first');
// disable the input fields for the row
$('input', row).attr('disabled', 'disabled');
// rename update_id to delete_id and re-enable the field
$('input[name="update_id[]"]', row).attr('name', 'delete_id[]').removeAttr('disabled');
// hide the row
row.hide();
}
This method no longer removes the table row from the DOM. However, it will disable the input fields contained in the row and adds a hidden input with the name beskrivelse_delete.
When the form is submitted, your PHP will now have a way to know which records need to be deleted.
foreach ($_POST['delete_id'] as $deleteId) {
$deleteId = (int)$deleteId;
$db->query("DELETE FROM faktura_materialer WHERE id = $deleteId");
}
Update: I've created a phpfiddle which has some improvements that you may wish to learn about. These points include:
Supporting deletion where JavaScript is not enabled
Using prepared statements (preferred to add_slashes)
Escaping output by using htmlspecialchars
Explicitly defining input ids to avoid guessing based on an incremental counter
I have been struggling with this for some time and cannot get it to work.
I have a form that sends a request to a php page. The php page returns the records
and outputs them as an html table. Certain fields in the table have a radio button, so that
the user can select that value. That value should be stored in an area, like a cart,
on the page. Here is what I have:
PHP page snippet:
while (oci_fetch($stmt)){
echo "<tr>\n"
. "<td class='v1'><input type='radio' name='price' value='STANDARD' id='rbt'>" . oci_result($stmt, 'STANDARD') . "</td>\n"
. "<td class='v2'><input type='radio' name='price' value='PREMIUM' id='rbt2'>" . oci_result($stmt, 'PREMIUM') . "</td>\n"
....
. "</tr>\n";
}
HTML code:
<td class='v1'><input type='radio' name='price' value='STANDARD' id='rbt'>798,4</td>
<td class='v2'><input type='radio' name='price' value='PREMIUM' id='rbt2'>965,87</td>
JavaScript:
$(document).ready(function(){
$("#rbt, #rbt2").click(function(){
alert($('input[name=fare]:checked').val());
});
});
This only shows an alert, which is not the goal.
So the question is: When a value, i.e. 798,4, is selected, it must be stored in the cart for a later calculation. Would JQuery solve this?
Any help would be appreciated!
$(document).ready(function(){
$("#rbt, #rbt2").click(function(){
//alert($('input[name=fare]:checked').val()); // this value come whcih is "STANDARD"
//so use
alert($(this).closest("td").text()); //alert 798,4
//to store in a div html use html();
$("divid").html($(this).closest("td").text());
});
});
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.