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
Related
Good Afternoon... I am trying to do the addition of textbox value and show in total textbox using onBlur but not able to do the same. Textbox are generated using foreach loop as per buffaloID base on database which having same name and id. ( Ref. Attached Image) For first textbox, the function gives the value but for next textboxes, not able to get the same.
My Modal Table Code.
#foreach ($buffalodata as $item )
<tr>
<td>{{$item->buffaloID}}</td>
<td><input type="number" id="eachmorningmilk" name="eachmorningmilk" value="00"></td>
<td><input type="number" id="eacheveningmilk" name="eacheveningmilk" value="00"></td>
<td><input type="text" id="eachtotalmilk" name="eachtotalmilk" value="00" readonly></td>
</tr>
#endforeach
JavaScript Code for Function to run onblur
$("#eachmorningmilk").blur(function(){
eachbmorning = parseInt($("#addmilkbuffalo #eachmorningmilk").val());
eachbevening = parseInt($("#addmilkbuffalo #eacheveningmilk").val());
var eachbuffalototalmilk = eachbmorning + eachbevening;
document.getElementById('eachtotalmilk').value=eachbuffalototalmilk;
})
Ref. Images
Please use the onchange method and assign unique id and name to each field. You can refer to the below code and it will work.
HTML
<tr>
<td>{{$item->buffaloID}}</td>
<td><input type="number" id="eachmorningmilk{{$item->buffaloID}}" name="eachmorningmilk{{$item->buffaloID}}" onchange="totalmilk({{$item->buffaloID}})" value="00"></td>
<td><input type="number" id="eacheveningmilk{{$item->buffaloID}}" onchange="totalmilk({{$item->buffaloID}})" name="eacheveningmilk{{$item->buffaloID}}" value="00"></td>
<td><input type="text" id="eachtotalmilk{{$item->buffaloID}}" name="eachtotalmilk{{$item->buffaloID}}" value="00" readonly></td>
JS
function totalmilk(id){
var morningmilk = "#eachmorningmilk"+id;
var eveningmilk = "#eacheveningmilk"+id;
var totalmilk = "eachtotalmilk"+id;
eachbmorning = parseInt($(morningmilk).val());
eachbevening = parseInt($(eveningmilk).val());
var eachbuffalototalmilk = eachbmorning + eachbevening;
document.getElementById(totalmilk).value=eachbuffalototalmilk;
}
I have a simple form with a text box. The user is able to add more text boxes by clicking a button.
I am dynamically creating the text boxes using javascript, however I have 2 issues:
1- I am not sure how to access the text boxes from the PHP file.
2- Whenever I click +addmore button on my html page it creates new text boxes but it clears the value of the previous ones.
Below is the html part:
<input type="text" id="program" name="program[]"> //Initital text box
<div><a onclick="CreateTxt()">+Add More</a></div> //Add more button
<input type="hidden" id="hid" name="hid" value="0">
<input type="submit" value="Next" name="submit1">
Below is javascript part:
var i = 1; // Global counter
var hidden_field;
function CreateTxt(){
var y = document.createElement("INPUT");
y.setAttribute("type", "text");
y.setAttribute("Name", "program" + i); //I am sure this is not working for the array names
y.setAttribute("class", "form-control");
document.getElementById('userdata1').innerHTML +=
'<label for="program"><br />Program</label>';
document.getElementById('userdata1').appendChild(y);
hidden_field = document.getElementById("hid").value = i; //passing the number of created textboxes
i++;
}
Below is PHP part:
<?php
session_start();
include('connection.php');
$id = $_SESSION['id'];
$i = $_POST['hid'];
if(isset($_POST['submit1'])){
if($i > 0){ //It means more than one text box exist
$program = [];
for ($j = 0; $j <= $i; $j++){
$program[$j] = $_POST['program'][$j];
$sql = $db->prepare ("UPDATE user SET program = ?, WHERE id = ? ");
$sql->bind_param("ss", $program[$j], $id);
$sql->execute();
}
}
}
?>
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;
});
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.'          </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.
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'>";