I have a table of items available for purchases which I am displaying on the site. I am using mysql to fetch all the items and display them in a table. Among others, the table contains this:
<input type="hidden" name="price" id="price'.$id.'"> //id is one part of MySQL query results
<input type="text" name="count_'.$id.'">
All this is displayed for around 200 items with ID being not completely in sequence (I found some JavaScript code that used for (i = 0; i < rows.length; i++) {}, however, with my IDs not being in a sequence, this is not a good option for me).
I would like to display a total of an order using JavaScript and I am not experienced when it comes to JS. I would be very thankful for your advices.
You coul duse jQuery:
function orderTotal()
{
var total=0;
$('input[name="price"]').each(function(){
var price = parseFloat($(this).val());
var amount = parseFloat($('input[name="count_'+$(this).attr('name').substring(5)+'"]').val());
total += price+amount;
});
return total;
}
Consider adding a class to each element that you want to count and see the answer below on stackoverflow. You should be able to have a counter for each occurrence of the class and show this variable in the html
How to getElementByClass instead of GetElementById with Javascript?
<div class="item"> ... <your inputs> ... </div>
I suggest you wrap them in another element, lets use div. Add a class to that, lets say moneyline
<div class="moneyline">
<input class="price" type="hidden" name="price" id="price'.$id.'"> //id is one part of MySQL query results
<input class="quantity" type="text" name="count_'.$id.'">
</div>
Im going to give the example with jQuery, and some button to trigger it:
$('#someButton').on('click', function(){
var total = 0;
$('.moneyline').each(function(){
var price = parseInt($(this).find('.price'), 10);
var quantity = parseInt($(this).find('.quantity'), 10);
total+= quantity*price;
});
alert( total );
});
Related
I have multiple forms on a page and also multiple input boxes with plus/minus signs.
I'm having trouble to get those input boxes to work seperately. Probably because of some wrong/same id's or something like that or maybe a wrong setup of my code. The thing is I can't find my error in the code and I don't get any errors in my console.
What I have:
function quantity_change(way, id){
quantity = $('#product_amount_'+id).val();
if(way=='up'){
quantity++;
} else {
quantity--;
}
if(quantity<1){
quantity = 1;
}
if(quantity>10){
quantity = 10;
}
$('#product_amount_'+id).val(quantity);
}
And my html:
//row 1
<div class="amount"><input type="text" name="quantity" value="1" id="product_amount_1234"/></div>
<div class="change" data-id="1234">
+
-
</div>
//row 2
<div class="amount"><input type="text" name="quantity" value="1" id="product_amount_4321"/></div>
<div class="change" data-id="4321">
+
-
</div>
I thought something like this would do the trick but it doesn't :(
$(document).ready(function(){
$('.change a').click(function(){
var id = $(this).find('.change').data('id');
quantity_change(id)
});
});
Any help greatly appreciated!
You should use closest() method to get access to the parent div with class change, then you can read the data attribute id's value.
var id = $(this).closest('.change').data('id');
alert(id);
Since you are already binding the click event using unobutrusive javascript, you do not need the onclick code in your HTML markup.
Also your quantity_change method takes 2 parameters and using both, but you are passing only one. You may keep the value of way in HTML 5 data attributes on the anchor tag and read from that and pass that to your method.
<div class="change" data-id="1234">
+
-
</div>
So the corrected js code is
$(document).ready(function(){
$('.change a').click(function(e){
e.preventDefault();
var _this=$(this);
var id = _this.closest('.change').data('id');
var way= _this.data("way");
quantity_change(way,id)
});
});
Here is a working sample.
My page shows some forms with content loaded from a database. Every row will get his own <input>. The ID of this input is equal for every row, except for the number that is attached to it, to make it unique. To make it more clear; this is how the form looks like when it loads 3 rows from the database:
<form>
<input id="Amount1" value="<?php echo $databaseValue; ?>" >
<input id="Amount2" value="<?php echo $databaseValue; ?>" >
<input id="Amount3" value="<?php echo $databaseValue; ?>" >
<input type="hidden" name="numberOfRows">
<input id="finalResult">
</form>
This is all done with the mysqli_array function. The value of numberOfRows is based on numRows function.
What I'd like to achieve is that javascript calculates the value of each existing input and put the result in finalResult, regardless the number of forms (because this may vary). If I make some changes to one of the values, the finalResult should update real-time.
What I've tried so far:
formnum contains the number of fields.
var a is created at the beginning, starting at 0. Inside it's function I create an ID, matching the fields on the page. All fields are named "Amount" + number. If this number equals the number of fields, the function will stop. This way the script won't be looking for fields that doesn't excist.
Then it gets the value of this field and adds the value to var b. var b is just created to store the value temporary, untill the function's over.
At the end the total is divided to 15. This is something extra I need. Nothing special on this line.
My code:
<script type='text/javascript'>
$(document).ready(function(){
var formnum = $("#numberOfRows").val();
var a;
var b = 0;
var formname = '#Amount';
for (a = 0; a < formnum; a++) {
var complete = formname.concat(a);
var completeContent = $(complete).val();
b = b + completeContent;
};
b = b.toFixed(2);
});
$(document).mousemove(function(event){
var formula_finalResult = b / 15;
var total_finalResult = Math.floor(formula_finalResult);
$("#finalResult").val(total_finalResult);
});
</script>
This doesn't do anything. It doesn't change the value. What's going wrong?
Make it simple:
$(function(){
var sum = 0;
// Selector to select all input whose id starts with Amount
$("input[id*='Amount']").each(function(){
sum += +$(this).val(); // Parsing as int and adding it to sum
});
$("#finalResult").val(Math.floor(sum/15)); // Storing the values
})
Assuming that all of the fields always have Amount at the beginning of their id attribute, you could use jQuery's ID selector to achieve this, without the need for any of the internal counters, etc.
I'm not entirely sure why you need to hook into the mousemove event, since the data should never change on the page (since it's being generated by PHP when the page is first loaded). The following code should achieve what you're looking for:
$(function() {
var total = 0;
$('input[id*="Amount"]').each(function() { total+= parseFloat( $(this).val() ); });
$('#finalResult').val( Math.floor( total / 15 ) );
});
Your code has an error Uncaught ReferenceError: b is not defined
see it in action here: http://jsfiddle.net/ca9vascj/
There's no reason to bring the mousemove event into this, I'm not even sure what that was needed for.
Like the above answers, here's a much simplified version. But instead of a partial ID selection, let's just give the form an ID, and then give all the needed elements inside that form a class that we can select by. We also no longer need to have the numberOfRows form element.
<form id="theForm">
<input class="formAmmount" value="5" />
<input class="formAmmount" value="10" />
<input class="formAmmount" value="27.5" />
<input class="formAmmount" value="4" />
<input class="formAmmount" value="9" />
<hr />
<input id="finalResult" />
</form>
And then our jQuery code can be reduced to this:
$(function(){
var total = 0;
$("#theForm .formAmmount").each(function(){
total += parseFloat(this.value, 10);
});
var final = Math.floor(total.toFixed(2) / 15);
$("#finalResult").val(final);
});
See it in action here: http://jsfiddle.net/ca9vascj/1/
You dont'need jQuery. The simplest way to do this is document.getElementsByTagName:
var inputs = document.getElementById('my-form').getElementsByTagName('input')
That's it. inputs.length will always get an actual count of inputs in your form. That's because getElementsByTagName() returns a NodeList object, containing a live view of the matching elements. This object is mutable; it will change in response to DOM mutations.
So if you need to get sum from all of the inputs:
function sum() {
var result = 0;
[].slice.call(inputs).forEach(function(input){
result += parseFloat(input.value)
});
return result;
}
If you are able to change the generated Html-Source I would suggest to give a new class to your InputElements.
<input id="Amount1" class="ElementToCount" value="<?php echo $databaseValue; ?>" >
Then you can calculate like that
var getSumOfElements = function() {
var Elements = $('.ElementToCount')
var sum=0
if (Elements && Elements.length>0) {
for (var i=0; i<Elements.length; i++) {
sum += Elements[i].val();
}
}
return sum
}
And to update the field you could register to the 'change'-Event
$('.ElementToCount).on('change', function() {
$('#finalResult').val(getSumOfElements());
})
Please help me out on this. I have Javascript like the following:
function calc() {
var table = document.getElementById(tableNum);
var rowCount = table.rows.length;
for (var i = 0; i < rowCount; i++) {
var totalNum[i] = document.formNum.txt1[i].value * document.formNum.txt2[i].value;
document.getElementById('totalCalc[' + i + ']').innerHTML = totalNum;
}
}
And HTML like this:
<table id="tableNum">
<form name="formNum" action="" id="formNum">
<tr>
<td><input type="text" name="txt1[]" onkeyup="calc()"/></td>
<td><input type="text" name="txt2[]" onkeyup="calc()"/></td>
<td><span id="totalCalc[]"></span></td>
</tr>
</form>
</table>
The number of input fields is unknown. No error, but totalCalc field is empty. Please tell me what I have done wrong. Thanks.
EDIT: I'm sorry, I forgot to mention both the input fields are in a table. Please check the edited code. Thanks.
EDIT: I'm actually working on a demo which the number of table row is defined by user, by clicking insert row button.
EDIT: Thanks Travis for the code. After a few changes, the code is working now. But only the first row is working. I'm thinking to get the length of the row and to use for loop for the text fields. <input type="text" name="txt1[<?php echo $rowLength;?>]" onkeyup="calc()"/> Does anyone have other ideas? Thanks.
The first thing seems wrong is
document.getElementById(tableNum);
should be
document.getElementById("tableNum");
Secondly,
var totalNum[i] =
should be
var totalNum =
Also, its not working, you can find it out quickly by debugging through firebug or chrome's integrated developer tool. Which will help you for syntax verification as well.
Here is what is going on.
HTML first
If you are going to reference these by indices, then use proper indices, like this
name="txt1[0]"
name="txt2[0]"
<span id="totalCalc[0]">
Javascript
document.getElementById(tableNum);
getElementsById expects a string, so this should be
document.getElementById("tableNum");
Since you are iterating, you only need one of these variables since it is immediately used (not a whole array):
var totalNum = instead of var totalNum[i]
When you access the form using dot notation, the brackets in the name messes that up, you need to do it like this:
document.formNum["txt1["+i+"]"].value instead of document.formNum.txt1[i].value
Vuala
When you make these minor changes, the code you used will actually produce proper results :) See this working demo: http://jsfiddle.net/69Kj7/ , also, here is a demo with 2 rows: http://jsfiddle.net/69Kj7/1/
For reference, this is the code in the demo:
html:
<table id="tableNum">
<form name="formNum" action="" id="formNum">
<tr>
<td><input type="text" name="txt1[0]" onkeyup="calc()"/></td>
<td><input type="text" name="txt2[0]" onkeyup="calc()"/></td>
<td><span id="totalCalc[0]"></span></td>
</tr>
</form>
</table>
js:
function calc() {
var table = document.getElementById("tableNum");
var rowCount = table.rows.length;
for (var i = 0; i < rowCount; i++) {
var totalNum = document.formNum["txt1["+i+"]"].value * document.formNum["txt2["+i+"]"].value;
document.getElementById('totalCalc[' + i + ']').innerHTML = totalNum;
}
}
if you wants to work with pure java script and here is the logical code
html
<form name="formNum" id="formNum" action="" >
<input type="text" name="foo[]" onkeyup="calc()" value="5"/>
<input type="text" name="foo[]" onkeyup="calc()" value="12"/>
<span id="totalCalc"></span>
</form>
js
var inputs = formNum["foo[]"];
var total = 1;
alert(inputs.length);
for (var i = 0; i < inputs.length; i++) {
total *= inputs[i].value;
}
alert(total);
working DEMO
I've figured out how to solve the problem. Just insert array after totalCalc, but not within totalCalc.
Thank you guys so much for helping me out :)
I am trying to use jquery to iterate through all '.invoice-lines' and generate a total by summing up all values in the '.amount-input' div.
AJAX dynamically generates the default values in '.amount-input' which can be manually changed by the user. I have been trying to create a function so that every time new data comes in using AJAX, a call will be made to the function updateTotal(), which iterates through all the non-empty 'amount-input' values and recalculates the total. I have been having a really tough time accomplishing this, and I would greatly appreciate any help.
JQuery - This is my jquery so far (pseudo code)
function updateTotal(){
var total=0;
for(i=0; i < $('.invoice-line').length; i++){
if($('.amount-input').eq(i).val() != empty)){
total += $('.amount-input').eq(i).val();
}
}
$('.total').val("$" + total);
}
Markup
<?
for(i=0; i < 25; i++){
echo' <div class="invoice-line">
<div class="prod-id-cell"><input type="text" class="prod-id-input"></div>
<div class="amount-cell"><input class="amount-input" type="text" /></div>
</div>';
}
?>
<div class="total">$0.00</div>
Make sure you cache the jQuery selection, otherwise you are doing 50 DOM traversals instead of 1:
var total=0, amounts = $('.amount-input'), len = amounts.length;
for(var i=0; i < len; i++){
total += +amounts[i].value;
}
Use the unary plus operator to convert the cell value from a string to a number. +"" will give you zero, so you don't need to check if the cell is empty, though you may want to check isNaN when validating the input.
Also, use val for input elements, but text for divs or spans.
$('.total').text("$" + total);
The basic syntax in pure JS is as follows:
var inputs = document.getElementsByClassName("amount-input");
var total = 0;
inputs.forEach(function (input) {
total += value;
});
The idea is that you get a collection of all the inputs in which you are interested, and then sum up the values using an external variable. If you wanted to expand this to include other inputs then you could use document.querySelectorAll("") with a CSS query selector to get the collection. (This is the same as the jQuery $("") selection syntax.)
Something like this should work:
function updateTotal() {
var total = 0;
$('.invoice-line').each(function (i, elem) {
total += parseFloat($(elem).find('.amount-input').val(), 10) || 0;
});
$('.total').val("$" + total);
}
You can use the change event to update the total amount everytime an input element is individually updated. Below is a simple example:
HTML:
<input class="invoice" type="text" value="0" />
<input class="invoice" type="text" value="0" />
<input class="invoice" type="text" value="0" />
<div id="total">0</div>
Javascript:
$('.invoice').change(function() {
var total = 0;
$('.invoice').each(function() {
total += parseFloat($(this).val());
});
$('#total').text(total);
});
You can see it working in this jsfiddle.
Shortly after posting, I was able to come up with my own solution as follows:
function updateTotal(){
var total=0;
for(i=0; i < $('.invoice-line').size(); i++){
currentAmount = Number($('.amount-input').eq(i).val().replace(/[^0-9\.]+/g,""));
total += currentAmount;
}
$('.total-number').text("$" + total.toFixed(2));
}
So the short version of this is: Can I traverse only the elements within the matched element of the selectors before the each()? Or is there a simpler way of getting what I want without an each() loop?
I thought this would be much easier, which makes me think I'm just missing some fundamental principle of element traversing with jquery.
So here's the scenario:
I have a table (and it is appropriate in this case), where each cell has a text input. The last input is read-only and is supposed to be the total sum of the other values entered on that row. I have a really messy js script for finding both the totals of each row and then the grand total of each row total.
Here's the basic HTML:
<table>
<thead>
<tr><th>Col 1</th><th>Col 2</th><th>Col 3</th><th>Total</th></tr>
</thead>
<tbody>
<tr id="row1"><td><input type="text" /></td><td><input type="text" /></td><td><input type="text" /></td><td class="total"><input type="text" readonly="readonly" /></td></tr>
<tr id="row2"><td><input type="text" /></td><td><input type="text" /></td><td><input type="text" /></td><td class="total"><input type="text" readonly="readonly" /></td></tr>
<tr id="row3"><td><input type="text" /></td><td><input type="text" /></td><td><input type="text" /></td><td class="total"><input type="text" readonly="readonly" /></td></tr>
</tbody>
</table>
The javascript will validate that the data entered is numerical, just to be clear.
So I have a event listener for each input for onchange that updates the total when the user enters data and moves to the next cell/input. Then I have a function called updateTotal that currently uses for loops to loop through each row and within that loop, each cell, and finally sets the input in the total cell to sum.
Quick note: I have included the code below to show that I'm not just looking for a hand out and to demonstrate the basic logic of what I have in mind. Please feel free to skim or skip this part. It works and doesn't need any debugging or critique.
This is what that looks like:
function updateTotal() {
table = document.getElementsByTagName("tbody")[0];
allrows = table.getElementsByTagName("tr");
grandtotal = document.getElementById("grand");
grandtotal.value = "";
for (i = 0; i < allrows.length; i++) {
row_cells = allrows[i].getElementsByTagName("input");
row_total = allrows[i].getElementsByTagName("input")[allrows.length - 2];
row_total.value = "";
for (ii = 0; ii < row_cells.length - 1; ii++) {
row_total.value = Number(row_total.value) + Number(row_cells[i][ii].value);
grandtotal.value = Number(grandtotal.value) + Number(row_cells[i][ii].value);
}
}
}
Now I am trying to re-write the above with jquery syntax, but I'm getting stuck. I thought the best way to go would be to use each() loops along the lines of:
function findTotals() {
$("tbody tr").each(function() {
row_total = 0;
$($(this) + " td:not(.total) input:text").each(function() {
row_total += Number($(this).val());
});
$($(this) + " .total :input:text").val(row_total);
});
}
But using $(this) doesn't seem to work in the way I thought. I read up and saw that the use of $(this) in an each loop points to each matched element, which is what I expected, but I don't get how I can traverse through that element in the each() function. The above also leaves out the grand_total bit, because I was having even less luck with getting the grand total variable to work. I tried the following just to get the row_totals:
$($(this).attr("id") + " td:not(.total) input:text").each(function() {
with some success, but then managed to break it when I tried adding on to it. I wouldn't think I'd need each row to have an id to make this work, since the each part should point to the row I have in mind.
So the short version of this is: Can I use the each loop to traverse only the elements within the matches, and if so, what is the correct syntax? Or is there a simpler way of getting what I want without an each loop?
Oh, one last thought...
Is it possible to get the numerical sum (as opposed to one long string) of all matched elements with jquery? I'll research this more myself, but if anyone knows, it would make some of this much easier.
You are trying to set your context incorrectly try this:
function findTotals() {
$("tbody tr").each(function() {
row_total = 0;
$("td:not(.total) input:text",this).each(function() {
row_total += Number($(this).val());
});
$(".total :input:text",this).val(row_total);
});
}
For more information about the context check out the jquery docs: http://docs.jquery.com/Core/jQuery#expressioncontext
There can be two parameters for a selector. The second parameter is the context htat that the search is to take place in. Try something like the following:
$('#tableID tbody tr).each(function(){
//now this is a table row, so just search for all textboxes in that row, possibly with a css class called sum or by some other attribute
$('input[type=text]',this).each(function(){
//selects all textbosxes in the row. $(this).val() gets value of textbox, etc.
});
//now outside this function you would have the total
//add it to a hidden field or global variable to get row totals, etc.
});