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;
});
Related
Let's say that I have this table with two rows:
<tr>
<td contenteditable="true" data-group1="<?php echo $_GET['group']; ?>" class="no1" id="nom1" name="nom1"><?php echo $item[$i]; ?></td>
</tr>
<tr>
<td contenteditable="true" data-group2="<?php echo $_GET['group']; ?>" class="no2" id="nom2" name="nom2"><?php echo $item[$i]; ?></td>
</tr>
The table is contenteditable which means, I can change the value inside the table. Currently, once the data have been manipulated, the data will be captured once the blur event is called. This is my script:
$(document).on('blur', '.no1', function(){
var group= $(this).data("group1");
var no = $(this).text();
});
$(document).on('blur', '.no2', function(){
var group= $(this).data("group2");
var no = $(this).text();
});
Based on this algorithm, let's say that I have manipulated the data from the first row which is referring to the class = "no1", it will then run this script as shown above:
$(document).on('blur', '.no1', function(){
var group= $(this).data("group1");
var no = $(this).text();
});
However, the number of rows for this table is not fixed. Therefore, this script is not helpful as we defined the function by ourselves based on the number of rows. Is there any way on how we can capture specific row information after calling the blur event so that we do not have to define quite a lot of similar functions.
You can use a common class on your trs and attach a blur event handler on its contenteditable td.
About your data-groupX attributes, just rename them all to data-group :
PHP
<tr class="common"> //Add your class here
<td contenteditable="true" data-group="<?php echo $_GET['group']; ?>" class="no1" id="nom1" name="nom1"><?php echo $item[$i]; ?></td>
</tr>
Javascript
$(document).on('blur', '.common td[contenteditable]', function(){
var group= $(this).data("group");
var no = $(this).text();
});
First Problem:
I want to add new field with a button, so everytime the button is clicked it will create new field. I try using Jquery but I am new in this kind of programming language, can someone help me? Am I doing it right?
HTML
<table>
<tbody>
<tr>
<td>
<?php
$n = 0;
$c = 0;
echo "<Select>";
do{
if($c>10){$n="";}
echo "<option>".$n.$c.":00</option>";
echo "<option>".$n.$c.":30</option>";
$c++;
}while($c<24);
?>
</td>
<td><input type="text"></td>
</tr>
</tbody>
</table>
<center><button id="addrow">Add Row</button></center>
Script
<script>
$(document).ready(function(){
$("#addrow").click(function(){
consoloe.log("asdasda");
$(tbody).append('<tr><td><?php
$n = 0;
$c = 0;
echo "<Select>";
do{
if($c>10){$n="";}
echo "<option>".$n.$c.":00</option>";
echo "<option>".$n.$c.":30</option>";
$c++;
}while($c<24);
?></td>
<td><input type="text"></td>
</tr>');
});
});
</script>
This is the error I get
This is The form look like
Second Problem:
I think I need to give a name or ID for this field, because I need to save it to a database, can you give me some advice about POST method to insert multiple records with mysqli? How can I loop the insert statement?
One things about your code first: 1. You neeed to also close the "select" element before ""
My advice solution:
Use jQuery to add new field like so
$("#addRow").click(function(){
$(tbody).append('<tr><td><select><option>Test1</option><option>Test2</option></select> </tr></td>);
});
Then to loop through your form before you submit it you can use PHP. All the fields would be in the $_POST[] suberglobal so foreach($_POST[] as $item){ //insert field in DB }
You can also use AJAX to submit the form and iterate over it's fields in jQuery:
$.each("tbody tr td select", function(field){
$.post("yourPHPfile.php", {name:field}, function(data){
//on success handler
});
});
Hope that helps!
You can do this by pure javascript , here is the example
var yourHTML="<td><select>";
yourHTML +="<option>--</option>";
yourHTML +="<option>--</option>";
yourHTML +="</select></td>";
yourHTML +="<td><input type='text'></td>";
function addRow(e){
var tab=e;
var rowCount=tab.rows.length;
var row=tab.insertRow(rowCount);
row.innerHTML=yourHTML;
}
Now call addRow() on click of button
$(document).ready(function(){
$("#addrow").click(function(){
addRow(document.getElementsByTagName("table")[0]);
});
});
LIVE http://jsfiddle.net/mailmerohit5/3outf4vm/
I am trying to create a simple calculation function and because of my lack of JS skills I just do not why it isn't working. The best I could get for now is a working 'calculate price' and a not working 'calculate total'. What I get from 'calculate total' is a result of 0.00 no-mater what the input is. So this is the JS I've got:
//Calculate price
$("#amount").live('click',function() {
var $itemrow = $(this).closest('.cust_row');
$quantity = $itemrow.find('#itemQty').val();
$price = $itemrow.find('#product_price').val();
$result = $quantity * $price;
$result = $result.toFixed(2);
$itemrow.find('#amount').val($result);
});
//Calculate total
$("#total").live('click',function() {
var $itemrows = $(this).closest('#invoice_items');
$price = parseFloat($itemrows.find('.amount').val());
$total = 0.00;
for (i = 0; i < $price.length; i++)
{
$total += parseFloat($price[i].value);
}
$result = parseFloat($total).toFixed(2);
$itemrows.find('#total').val($result);
});
and the html bit:
<div id="invoice_items">
<div class="cust_row">
<div class="cust_row_40"><strong>Product Name</strong></div>
<div class="cust_row_30"><strong>Category</strong></div>
<div class="cust_row_10"><strong>Quantity</strong></div>
<div class="cust_row_10"><strong>Price</strong></div>
<div class="cust_row_10"><strong>Amount</strong></div>
</div>
<div class="cust_row">
<div class="cust_row_40"><input name="product_name[]" class="input_tbl" id="product_name" tabindex="1"/></div>
<div class="cust_row_30"><input name="category_name[]" class="" id="category_name" readonly="readonly" /></div>
<div class="cust_row_10"><input name="itemQty[]" class="itemQty" size="4" id="itemQty" tabindex="2"/></div>
<div class="cust_row_10"><input name="product_price[]" class="product_price" size="5" id="product_price" readonly /></div>
<div class="cust_row_10"><input name="amount[]" class="amount" id="amount" size="5" readonly /></div>
</div>
<div class="clear_b"></div>
<span> <img src="../img/icon-plus.png" alt="Add" title="Add Row" /> Add Item</span>
<div style="text-align: right;">Total: <input name="total[]" class="" id="total" size="5" readonly /></div>
</div>
In this line
$price = parseFloat($itemrows.find('.amount').val());
Isn't this parsing a float out of an array of your inputs? If you remove that, you should be able to loop through your inputs, and the parse float inside the loop will be enough.
$price = $itemrows.find('.amount').val();
$price = parseFloat($itemrows.find('.amount').val());
You're not going to get a list from that - parseFloat only parses one float, despite it looking like you're expecting several $itemrows.
Instead of this:
$price = parseFloat($itemrows.find('.amount').val());
$total = 0.00;
for (i = 0; i < $price.length; i++)
{
$total += parseFloat($price[i].value);
}
Try this:
<div id="invoice_items">
<div class="cust_row_labels">
<!-- I changed this... -->
so we dont grab it accidentally when trying to get total calculation. There are other ways to go about this but this was easiest.
// Given a "cust_row", calculate a price
function calcPrice( $cust_row ) {
// The $ in cust_row is a -loosely- defined way
// indicating something is a "jQuery wrapped" element
// (not a js coding thing, but more of a jQuery ease of use thing)
// Below I'm taking your price calculating code and making it
// more reusable
var quantity = $cust_row.find('#itemQty').val();
var price = $cust_row.find('#product_price').val();
var result = quantity * $price;
return result.toFixed(2);
}
// We can now use that function whenever, not just when "#amount" is clicked
// but we still have to tie them #amount and the method back together somehow
$("#amount").live( "click", function() {
var $theAmount = $( this ),
$customerRow = $theAmount.parents( ".cust_row" );
$theAmount.val( calcPrice( $customerRow ) );
} );
// function for finding all totals
function overallTotal() {
var total = 0;
$( "#invoice_items .cust_row" ).each( function() {
total += calcPrice( $( this ) );
// "this" is a weird moving target, in this case
// its each cust_row as we cycle through them
} );
etc...
Your variables don't need to start with dollar signs, ie: I used prices instead of $prices, and $total could just be total (assuming you are consistent throughout whichever you choose). You probably saw that often because of jQuery examples, but people tend to use $ as a shorthand to indicate that its a jquery thing you're dealing with.
Also, it seems as if - given the presence of something called "add row", you'll want to append more cust_row things in here, but you may run into problems given that some things are IDs. An ID should be unique on a page - once you add another row you'll have more than one thing with an ID of amount. Change those ids to classes, then rewrite the appropriate selectors to start with . instead of #
I have an array having 2-3 titles. eg. 'Get 20% Off' , 'Receive 40% Savings' , 'Grab 10% discounts' etc. I would like to get the numeric value before '%' sign. and pass this numeric value into a html form as inputs. and in return the form would calculate a percentage amount. and display all the results.
Right now i have managed to make this work for a single title. but i am not able to get a array of titles.
my code is as follows -
//code for getting all the titles //putting it into an array called '$array'
foreach($array as $str) {
if(preg_match('/(\d+)\%/i' ,$str,$m)) {
echo $m[1],"\n"; ?>
<?php }
} ?>
//the above code extracts the amount before the percentage off sign. and the below code passes it as a input to the form (name=a). and other input (name=b) is coming from a different source. thats working fine. for calculation consider that input to be 100. I would need to calculate the percent value w.r.t 100. for eg- if input a is 5, then another input b is 100. the value to be outputted would be 5.
<form name="form1">
<input type="text" name="a" value="<?php echo $m[1]; ?>" size=5>
<input class="budget-sidebar" type="text" name="b" id="amount" size=5>
the below html is used for displaying the calculated value and submitting the form.
<input type="text" name="total1" value="ans1" size=5 maxlength=4>
<input type="button" value="Calculate" onClick="calc1(this.form)">
</form>
the below javascript function is responsible to take the inputs and calculate the value and displaying it.
<SCRIPT LANGUAGE="JavaScript">
<!-- Begin
function calc1(form) {
a = form.a.value/100;
b = a*form.b.value;
form.total1.value = b;
}
// End -->
</script>
i have posted a similar question requesting for different suggestions & this is supposed to be a different query. thanks.
try to convert form value to integer before performing calculation
function calc1(form) {
a = parseInt(form.a.value, 10)/100;
b = a* parseInt(form.b.value, 10);
form.total1.value = b;
}
And you will have to round the value to avoid to get strange value
[Edit]:
And to get multi string some thing like this will may work (no test sorry)
// php
$values = array();
foreach($array as $str) {
if(preg_match('/(\d+)\%/i' ,$str,$m)) {
$values[] = $m[1];
}
}
// for html
<form name="form1">
<?php for($i = 0; $i < count($values); $i++) { ?>
<input type="text" name="a<?php echo $i ?>" value="<?php echo $values[i]; ?>" size=5>
<?php} ?>
<input class="budget-sidebar" type="text" name="b" id="amount" size=5>
// javascript
function calc1(form) {
var i = 0, a = 0;
while (form["a" + i]) {
a += parseInt(form["a" + i].value, 10);
i++;
}
b = a/100 * parseInt(form.b.value, 10);
form.total1.value = b;
}
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.