I am trying to understand how write a total function to call on multiple input-steppers that I used from a library. I did read the documentation of the library on how to call things. Now I can increment & decrement 1 stepper and multiply by a variable, and display in total field. I can't figure out how to change the total function so it can be used on all steppers and displayed in 1 total field. Do I need if else or a loop? I'm not sure how to start. Also not sure how to add library here?
$(document).ready(function(){
$(function () {
// Document ready
$('.input-stepper').inputStepper();
});
});
var value1 = 0.95;
var value2 = 4.00;
var value3 = 2.00;
// These are to call inputs
$('#amount1').on('increase', function (e, amount, plugin) {
calculate();
});
$('#amount1').on('decrease', function (e, amount, plugin) {
});
$('#amount2').on('increase', function (e, amount, plugin) {
});
$('#amount2').on('decrease', function (e, amount, plugin) {
});
$('#amount3').on('increase', function (e, amount, plugin) {
});
$('#amount3').on('decrease', function (e, amount, plugin) {
});
// these are to call stepper buttons
$('[data-input-stepper-increase] ').click(function(){
});
$('[data-input-stepper-decrease]').click(function(){
});
function calculate(){
var total = 0;
var quantity = parseInt($('#amount1 ').val());
total = value1 * quantity;
console.log(total);
$('#TotalField').val(total.toFixed(2));
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h3>$0.95 value</h3>
<button data-input-stepper-decrease>-</button>
<input id="amount1"type="text" value="0">
<button data-input-stepper-increase >+</button>
<h3>$4.00 value</h3>
<button data-input-stepper-decrease>-</button>
<input id="amount2"type="text" value="0">
<button data-input-stepper-increase>+</button>
<h3>$2.00 value</h3>
<button data-input-stepper-decrease>-</button>
<input id="amount3"type="text" value="0">
<button data-input-stepper-increase>+</button>
<label>Total</label><input type="text"
class="" id="TotalField" name="TotalField" />
Here is link to library https://github.com/AanZee/input-stepper
link to codpen I am working on
http://codepen.io/Ongomobile/pen/kXogvZ?editors=1111
About the binding, both increase and decrease could be bound in one go:
$('[id^=amount]').on('increase decrease', calculate);
Instead of '[id^=amount]', you could also use '#amount1,#amount2, etc', but better yet would be to have a common class
For easier summarizing the values should be in a collection, such as var values = [0.95, 4.00, 2.00]; (although you could also put them in (data) properties on the elements)
Then, if boxes is the jQuery variable of the inputs, you could summarize with:
var total = 0;
boxes.each(function(ind,box){ total+= values[ind] * $(box).val();});
Finalizing, the whole would look like:
var boxes = $('[id^=amount]').on('increase decrease', calculate); //bind the elements and assing to the boxes variable in one go
var values = [0.95, 4.00, 2.00];
function calculate(){
var total = 0;
boxes.each(function(ind,box){ total+= values[ind] * $(box).val();});
console.log(total);
$('#TotalField').val(total.toFixed(2));
}
codepen
I believe the below solution is what you're looking for, judging from your current code:
var value1 = 0.95;
var value2 = 4.00;
var value3 = 2.00;
// these are to call stepper buttons
$('[data-input-stepper-increase] ').click(function(){
calculate();
});
$('[data-input-stepper-decrease]').click(function(){
calculate();
});
function calculate(){
var total = 0,
quantity1 = parseInt($('#amount1 ').val()),
quantity2 = parseInt($('#amount2').val()),
quantity3 = parseInt($('#amount3 ').val());
total = (value1 * quantity1)+(value2 * quantity2)+(value3 * quantity3);
$('#TotalField').val(total.toFixed(2));
}
Related
I have a checkout page, where I would like to implement a new feature: subtract from total cart value a certain amount, introduced in an input.
Example: There is 1 item in cart, with value of 10.00$. If user typed 100 in that input, then he would have a discount of 1$ (100 pts = 1$ in this example) and the final value of the cart would be 9.00$. Since I'm using some integrated apps for getting/calculating item value, total cart value, etc. I would like to get some generic code, which I would eventually adjust, to link with my existing code, functions, etc.
The function I have should have these features:
create form
get input value
subtract used points from user's total amount (for example totalPts = 1000)
subtract from cart total value used points, converted into $ (100pts = 1$)
For now, my function looks like this:
function appendRefferalPoints() {
const totalPts = 1000;
// creating form - ok
$form = $('<form id="refForm" class="coupon-form" action></form>');
$form.append(
'<input type="text" id="refValue" name="refInput" class="coupon-value input-small" >'
);
$form.append('<button type="submit" class="btn">Aplica</button>');
$("body").append($form);
// get input value - not ok
$("#refForm").submit(function () {
let value = 0;
$.each($("#refForm").serializeArray(), function (i, field) {
value[field.name] = field.value;
});
});
// subtraction from totalPts logic - not ok
let rez = totalPts - value;
console.log("Final Rez: " + rez);
// subtraction converted pts from cart value logic
}
Now when I submit the form I only url changes from /checkout#/cart to /checkout/?refInput=512#/cart
function appendRefferalPoints() {
const totalPts = 1000;
let cartValue=10;
let discount=0;
let inputValue = 0;
// creating form - ok
$form = $('<form id="refForm" class="refForm coupon-form" ></form>');
$form.append(
'<input type="text" id="refValue" name="refInput" class="coupon-value input-small" value="100" >'
);
$form.append('<button id="btnClick" class="btn">Aplica</button>');
$("body").append($form);
$(document).on("submit", "#refForm", function(e){
//getting input value while submitting form
inputValue=$("#refValue").val();
//converting 100 pts to 1 dallor
discount=inputValue/100;
//calculating balance pts
let balancePts = totalPts - parseInt(inputValue);
//calculating final amount
let finalCartValue=cartValue-discount;
alert("finalCartValue"+finalCartValue);
});
}
appendRefferalPoints();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
I have three DIV whose content are integer values and are updated frequently from another source. My main idea here was to take the content of the three divs parse it into float or integer , add them and display the total in another div. I am looking forward to handle the content in div using a onchange() function, because the the content in them will be changing frequently. Below is my code, its currently not working, i will really appreciate it if you give me a hand of help with this.
The content in this divs will be frequently updated using a text input, you can create a text inout that manipulates the first div then displays the whole sum
Thanks in advance.
<script>
function total() {
var value1 = parseFloat($('#div1').innerHTML ()) || 0;
var value2 = parseFloat($('#div2').innerHTML ()) || 0;
var value3 = parseFloat($('#div1').innerHTML ()) || 0;
var total;
total=value1 + value2 + value3;
$('#total').html(total);
}
</script>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
</head>
<body >
<div id="mywraper">
<div id="div1" onchange="total()">
4
</div>
<div id="div2" onchange="total()">
5
</div>
<div id="div2" onchange="total()">
6
</div>
</div>
<div id="total_div">
Total $<span id="total"></span>
</div>
</body>
</html>
Use this html()
<script>
function total() {
var value1 = parseFloat($('#div1').html()) || 0;
var value2 = parseFloat($('#div2').html()) || 0;
var value3 = parseFloat($('#div1').html()) || 0;
var total;
total=value1 + value2 + value3;
$('#total').html(total);
}
</script>
Try this:
function total() {
// fetch text using 'text' method and then convert string into number using '+' operator
var value1 = +$('#div1').text() || 0;
var value2 = +$('#div1').text() || 0;
var value3 = +$('#div1').text() || 0;
var total = value1 + value2 + value3;
$('#total').html(total);
}
http://jsfiddle.net/uxajjk1b/2/
Use text() instead of innerHTML, like so:
<script>
function total() {
var value1 = parseFloat($('#div1').text()) || 0;
var value2 = parseFloat($('#div2').text()) || 0;
var value3 = parseFloat($('#div1').text()) || 0;
var total;
total=value1 + value2 + value3;
$('#total').html(total);
}
</script>
I didn't really want to answer, as this might be difficult to solve due to the fact that we have no idea how the values are updated in the first place. However, I ended up doing relatively extensive example, so here we are.
So as mentioned before, onChange requires user input or action to detect any change. So that means your total() would only trigger once when the page is loaded ( assuming it's placed right before </body> ).
The best method would be to also stick the total() inside the original function that changes the values inside the html elements. This way total() is also triggered each time.
I couldn't resist making the total() more dynamic. This way, if you add or remove those child divs, the javascript won't need to be updated.
Here's a link to the original jsfiddle
var parentContainer = $('#mywraper');
function total() {
var values = {}; // Optional****
var total = 0;
// Loops through parent containers children ( in this case div elements ).
parentContainer.children().text(function( i, val ) {
var value = parseInt( val );
// Creates a variable where the variable name is based on the current elements index and value is based on the text inside the element.
values[ 'child_' + (i+1) ] = value; // Optional****
// Sums up all the values
total += value;
});
// The optional lines enable you independently check each value, for example:
// console.log( values.child_1 )
// Push total into the #total element.
$('#total').html( total );
}
total();
Here's an example where the values are updated with a click event. So what you do is just add the total() inside the click event as well.
function total() {
var parentContainer = $('#mywraper'),
total = 0;
parentContainer.children().text(function( i, val ) {
total += parseInt( val );
});
$('#total').html( total );
}
total();
$('#updateBtn').on("click", function() {
$('#mywraper').children().text(function( i, val ) {
return parseInt( val ) + 1;
});
total();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="mywraper">
<div>4</div>
<div>5</div>
<div>6</div>
</div>
<div id="total_div">
Total $<span id="total"></span>
</div>
<button id="updateBtn">Update values</button>
How to calculate using jquery or Javascript in Codeigniter as below requirement
I have 3 input element to calculate after user complete they form element :
1, Quantity
2, Unitprice
3, Total.
By Total = quantity * unitprice.
<td><?php echo form_input('quantity','',' class="form-control"')?></td>
<td><?php echo form_input('unitprice','',' class="unit form-control" placeholder="unit pricee"')?></td>
<td><?php echo form_label('','total','class="form_control"')?></td>
I try to write javascript like this
<script type="text/javascript">
$(document).ready(function () {
$('.unitprice').keyup(function () {
Calculate();
});
});
function Calculate() {
var quantity = document.getElementsByClassName("quantity").val();
var unitprice = document.getElementsByClassName("unitprice").val();
var total = quantity * unitprice;
$('.total').val(total);
}
</script>
But it is not work
Thanks advance!!!!
Try like this:
$(function(){
$('.qty, .unit').on('blur', function(e){
var qty = parseFloat( $('.qty').val() ),
unit = parseFloat( $('.unit').val() );
if( isNaN(qty) || isNaN(unit) ) {
$('.result').text('');
return false;
}
var total = qty * unit;
$('.result').text( total );
});
});
DEMO
Here's a basic example, since I was bored. Fiddle - http://jsfiddle.net/sgnl/44ts8ucf/1/
html
<input type="text" id="quantity" class="calc_element"> Quantity
<input type="text" id="unit_price" class="calc_element"> Unit Price
<div id="total"></div>
javascript
// get some IDs or classes on your elements to target them easily
var total = $('#total');
// bind an event that triggers on KEYUP
$('.calc_element').on('keyup', function(){
// when triggered get the values from the input elements
// via jQuery's '.val()' method
var quantity = $('#quantity').val() || 1;
var unit_price = $('#unit_price').val();
var result = (quantity * unit_price) + " total";
// set the innerHTML of the div to your calculated total
total.html(result);
});
YMMV, thats the jist of it, some tweaking will need to be down for your code.
I am trying to use Javascript to calculate sum of order in one big form. Each product has its own price, however, there are more prices tied with some products. Each product has it's own price, but if a customer orders bigger quantity of this product, the price will drop to a value that is specified in a database table.
To simplify, the shopping form for one item looks something like this.
<input name="id" value="'.$id.'" type="hidden">
<input name="price_'.$id.'" value="'.$price.'" type="hidden">
<input name="quantity_'.$id.'" type="text" onchange="calculateTotal()">
I have a table with the discounts: itemId, minimumQuantity, priceAfterDiscount. There can be more than one discounts connected with one item. The MySQL query works with LEFT JOIN of Items and Discounts tables.
calculateTotal() calculates the total of order after every input change.
What I would like to do, is to check if the quantity of certain product is greater than the value needed for the discounts and if so, I would like to change the value of the input with price from item's regular price to the discounted one. Then, calculateTotal() will use that price and update the total.
To do so, I think I can do something like adding more hidden inputs with values of all discounts. The function would check if there is a discount linked to every item and if so, it will check if the quantity is greater than requiredQuantity and if this condition is met, it will update the value of price hidden input. Please keep in mind that there can be multiple discounts connected to one item - the function should find the lowest price that meets requiredQuantity.
I am trying to do this - create the hidden inputs and somehow parse them in javascript, but I am just not able to figure this out. I tried my best to explain the problem, however, if my explanation is not sufficient, I will try to answer your questions regarding my issue.
I hope you are able and willing to help me. Thanks for help in advance.
Perhaps something like this example.
CSS
.itemLabel, .currentPrice, .subTotal {
display: inline-block;
width: 40px;
}
#myTotal {
border:2px solid red;
}
HTML
<fieldset id="myInputs"></fieldset>
<div id="myTotal"></div>
Javascript
var myInputs = document.getElementById('myInputs'),
myTotal = document.getElementById('myTotal'),
order = {
total: 0
},
items = {
foo: {
1: 0.5,
100: 0.25
},
bar: {
1: 1,
100: 0.5
}
},
totalNode;
function calculateTotal() {
var newTotalNode;
Object.keys(order).filter(function (key) {
return key !== 'total';
}).reduce(function (acc, key) {
order.total = acc + order[key].subTotal;
return order.total;
}, 0);
newTotalNode = document.createTextNode(order.total.toFixed(2));
if (totalNode) {
myTotal.replaceChild(newTotalNode, totalNode);
totalNode = newTotalNode;
} else {
totalNode = myTotal.appendChild(newTotalNode);
}
console.log(JSON.stringify(order));
}
calculateTotal();
Object.keys(items).forEach(function (key) {
var div = document.createElement('div'),
label = document.createElement('label'),
price = document.createElement('span'),
input = document.createElement('input'),
subtotal = document.createElement('span'),
priceNode,
subTotalNode;
order[key] = {
quantity: 0,
subTotal: 0,
price: items[key]['1']
};
priceNode = document.createTextNode(order[key].price.toFixed(2));
subTotalNode = document.createTextNode(order[key].subTotal.toFixed(2));
label.className = 'itemLabel';
label.setAttribute("for", key);
label.appendChild(document.createTextNode(key));
price.className = 'currentPrice';
price.id = key + 'CurrentPrice';
price.appendChild(priceNode);
input.id = key;
input.name = 'myFormGroup';
input.type = 'text';
input.addEventListener('change', (function (key, order, priceNode, subTotalNode) {
return function () {
var value = +(this.value),
newPriceNode,
newSubTotalNode;
Object.keys(items[key]).sort(function (a, b) {
return b - a;
}).some(function (quantity) {
if (value >= quantity) {
order.price = items[key][quantity];
newPriceNode = document.createTextNode(order.price.toFixed(2));
priceNode.parentNode.replaceChild(newPriceNode, priceNode);
priceNode = newPriceNode;
return true;
}
return false;
});
order.subTotal = order.price * value;
newSubTotalNode = document.createTextNode(order.subTotal.toFixed(2));
subTotalNode.parentNode.replaceChild(newSubTotalNode, subTotalNode);
subTotalNode = newSubTotalNode;
calculateTotal();
};
}(key, order[key], priceNode, subTotalNode)), false);
subtotal.className = 'subTotal';
subtotal.id = key + 'SubTotal';
subtotal.appendChild(subTotalNode);
div.appendChild(label);
div.appendChild(price);
div.appendChild(input);
div.appendChild(subtotal);
myInputs.appendChild(div);
});
On jsFiddle
I've an html page which has many dynamically created input boxes. The number of text boxes vary each time.
I want to calculate the sum of the numbers the user has entered, and disply it. When the user delete one number the sum should auto calculate.
How can i do it with javascript?
Thanks
In jQuery something like this should work with a few assumptions:
$('.toAdd').live('change', function() {
var total = 0;
$('.toAdd').each(function () {
total += $(this).val();
});
$('#total').val(total);
});
The assumptions being that your input fields all have the class 'toAdd' and that your final input field has an ID of 'total'.
In pure JS:
var elems = document.getElementsByClassName('toAdd');
var myLength = elems.length,
total = 0;
for (var i = 0; i < myLength; ++i) {
total += elems[i].value;
}
document.getElementById('total').value = total;
Let me elaborate when I review my notes but here is a high level answer that I believe will work... (My Java Script is very rusty)...
Make the input boxes share an attribute (or use tag) so you can get a collection to walk through no matter the size... Then on the onkeyup event on every input call this function that will sum the totals. Put the result into another entry with the ID you know beforehand...
You will have to validate input because if one of them is not a number then the total will also be "NAN"
Okay here is a complete working example you can build off of that I just threw together: It obviously needs a great deal of polishing on your end...
<html>
<head>
<script language="javascript">
function AddInputs()
{
var total = 0;
var coll = document.getElementsByTagName("input")
for ( var i = 0; i<coll.length; i++)
{
var ele = coll[i];
total += parseInt(ele.value);
}
var Display = document.getElementById("Display");
Display.innerHTML = total;
}
</script>
</head>
<body>
<input onkeyup="AddInputs()" />
<input onkeyup="AddInputs()" />
<input onkeyup="AddInputs()" />
<span id="Display"></span>
</body>
</html>