I'm not sure how best to ask this question, I'm new to Javascript and although I have got this far, I don't know how to shorten the code anymore than I have to make it easier to read so...
Here's my code:
var price;
function getInkPrice(arrayOfArrays){
var inkName = 'Epson S60600';
columnNumber = 7;
arrayOfValues = arrayOfArrays.filter(function(r){return true;});
var inkPrice = document.getElementById("ink-price");
showPrice(inkPrice, arrayOfValues, columnNumber, inkName);
}
function getMileagePrice(arrayOfArrays){
var mileageName = 'Mileage';
columnNumber = 1;
arrayOfValues = arrayOfArrays.filter(function(r){return true;});
var mileagePrice = document.getElementById("mileage-price");
showPrice(mileagePrice, arrayOfValues, columnNumber, mileageName);
}
function showPrice(el, arrayOfArrays, col, obj) {
const results = arrayOfArrays.filter(r => r[0] === obj);
const newResult = results [0][col].toFixed(2);
el.textContent = newResult;
price = newResult;
combinePrice()
}
function combinePrice() {
alert('your total price is ' + price + price);
}
RESULTS
getInkPrice = 4.19
getMileagePrice = 0.55
Basically the getInkPrice() and getMileagePrice() setups the next function showPrice() to filter the results that I require.
The showPrice() function then filters the results and adds them to a div allowing me to display them in my html page.
Finally I created a global variable called 'price'. Once getMileagePrice() has finished, it calls the combinePrice() function which alerts the combined price (or it will do once I figure this out).
So, the combinePrice() function currently displays:
your total price is 4.194.19
That is wrong, it should display:
your total price is 4.74 (which is the 4.19 + 0.55).
I understand what part of the problem is but I can't figure to how I go about fixing it.
So my showPrice() function is doing the hard work in getting the values, it then stores that in the price variable. How does the price variable know what the value is seeing as both the getInkPrice() and getMileagePrice() are using it so it defaults to the first value.
So my global variable stores the 4.19 from the first function and not getting the value form the second function. Finally the 4.19 is not being classed as a number and therefor not adding them together. I could be wrong though.
Any ideas how I can fix this?
There are two issues here:
When you do 'your total price is ' + price + price, the pluses are evaluated from left to right, so even the second + is actually string + rather than number +. You can solve this issue by doing 'your total price is ' + (price + price).
You have only one variable price, but you seem to need two separate ones, one for ink and the other one for mileage.
Possible solution:
Define price where you will sum results of your functions
Reset price value (to zero) each time before getInkPrice & getMileagePrice called
Add new result value to price inside of showPrice instead of redefining it
Get sum from price whereever you need
var price; // [1]
price = 0; // [2] reset value somewhere before getInkPrice & getMileagePrice called
function getInkPrice(arrayOfArrays){
var inkName = 'Epson S60600';
columnNumber = 7;
arrayOfValues = arrayOfArrays.filter(function(r){return true;});
var inkPrice = document.getElementById("ink-price");
showPrice(inkPrice, arrayOfValues, columnNumber, inkName);
}
function getMileagePrice(arrayOfArrays){
var mileageName = 'Mileage';
columnNumber = 1;
arrayOfValues = arrayOfArrays.filter(function(r){return true;});
var mileagePrice = document.getElementById("mileage-price");
showPrice(mileagePrice, arrayOfValues, columnNumber, mileageName);
}
function showPrice(el, arrayOfArrays, col, obj) {
const results = arrayOfArrays.filter(r => r[0] === obj);
const newResult = results [0][col].toFixed(2);
el.textContent = newResult;
price += newResult; // [3] add to total price
combinePrice();
}
function combinePrice() {
alert('your total price is ' + price); // [4] get it when you wish
}
Related
I am using a Firebase db. I have a value i display on my page that increments and updates itself which can be seen on the web page.
I also have predetermined total value.
I want to create a sum that has the total value be decreased by the previously mentioned dynamic value. and send an alert to the user on the web page when it hits 0.
However I can't seem to get this to work, this is what I tried:
// here I create the sum for the total amount
var total = 0;
function getData(){
for (var i = 0; i < HoeveelheidArr.length; i++) { //my arrawy from user input which i extracted
total += parseInt(HoeveelheidArr[i]);
}
}
//here i push the values to my DB
function writeData(){
firebase.database().ref("Exercise").set({
totalReps: total,
totalRepsLeft: progressLeft,
});
//Here I update the DYNAMIC value on my page it gets incremented by 1 by my arduino on an event. this works
var progressList = document.getElementById("progressList");
var wemosRep = function(element, value){
element.textContent = value;
}
//get value from db and auto pass update if change in value
var startWemosRep = firebase.database().ref('Reps/Value');
startWemosRep.on('value', function(snapshot){
wemosRep(progressList,snapshot.val());
});
//now the part that doesnt work... Just like before I try to first create the sum and then display it on my page if this value changed.
progressLeft = parseInt( startWemosRep) - total ; //this doesnt!
var pageProgressLeft = document.getElementById("progressLeft");
var repLeft = function (element, value){
element.textContent = value;
};
var startTotalRep = firebase.database().ref('Exercise/progressLeft');
startTotalRep.on('value', function(snapshot){
repLeft(pageProgressLeft, snapshot.val());
});
}
// I get the total value i pushed in my DB named totalGet!
function gotData(data){
firebase.database().ref('Exercise').once('value').then (function(snapshot){
var totalGet = snapshot.val().totalReps;
document.getElementById("totalList").innerHTML=totalGet;
})
The progressLeft variable doesn't get returned, that is what it boils down to. It doesn't display on my page nor do I know if it works. I tried everything at this point I cant see the end of the tunnel. Hope you can help me out with this.
Am trying to define a certain function here to calculate the total
var total =0;
var movie_prices = [];// create the movie prices array but it is waiting for values from user selections like 14,16,35//
function calculateTotal(arguments){ //this is the called function//
var len = arguments.length
for(vari=0; i<len;i++){
total+= parseInt(arguments[i]); return total;
}
}
This function will display the total by determining which movies are checked;
function displayTotal(){
var obj = document.getElementById('flicks'); //flicks is an id to the table element containing checkboxes//
var top = obj.getElementByTagName('input');// reference to checkboxes of input type//
var leng = top.length;
for(vari=0; i< leng;i++){
if(top[i].checked ){
movie_prices.push(top[i].value;);
}
}
call to the calculateTotal function with movieprices array as an argument;
calculateTotal(movie_prices);
window.alert("The total amount you now owe is:" + total); // display total//
}
Two things I see so far. Line seven should be a comment so if you don't have it commented out at runtime that would be giving you errors.
Also the method top[i].value appears to be undefined. Where have you declared value in your code?
I have this code that I want to take the current price in <span id="price">, add another price (for example, 1000) and then change <span id="price"> to the new price. When I try, the text in <span id="price"> just disappear. Why does it do that and how do I fix the code?
The JavaScript code:
function getProductPrice()
{
return obj.price;
}
function getCurrentPrice()
{
var price = $("#price").val();
var price = $("#price").text();
return price
}
function getTotalPrice()
{
var total = $(getCurrentPrice() + getProductPrice()).val();
var total = $(getCurrentPrice() + getProductPrice()).text();
return total;
}
$("#price").val(getTotalPrice());
$("#price").text(getTotalPrice());
(obj.price is the price I want to add)
It's probably disappearing because the value you're setting to it isn't actually there(because technically, you're adding a string to an integer if I'm guessing right). You can try something like
var price = parseInt($('#price').text()); //convert the text to integer
var addPrice = 1000; //the price you wanted to added
var newPrice = price + addPrice; // add them up
$('#price').text(newPrice); //voila!
You can change the 1000 to obj.price since it's the thing you wanted to added, for example.
Fiddle right here by the way.
You are trying to use the concatenation of getCurrentPrice() and getProductPrice() as jQuery selectors, but everything else about your question suggests that they are numbers.
Just use the numbers.
Don't concatenate them. Don't search the DOM for an element that matches them. Don't try to read the value or text content of that element.
i think you don't have to use jquery for total. try this:
var total = parseInt(getCurrentPrice()) + parseInt(getProductPrice());
Try this:
function getProductPrice() {
return obj.price;
}
function getCurrentPrice() {
var price = $("#price").text();
return price;
}
function getTotalPrice(){
var total = getCurrentPrice() + getProductPrice();
return total;
}
$("#price").text(getTotalPrice());
I have this javascript, jquery function, (below)
It gets the text inside each table cell (of class="total_item_price") of a table.
It puts it into an array (prices_array)
Adds up prices_array and formats them to 2 Decimal Places.
Then outputs it into the total_order_price, or returns it if do_request isset.
Problem: I have a function that deletes a item from the basket, then calls this function (getTotalPrice) to update the prices field. This part does not work correctly, and is not producing the correct price.
Basically, I need this function, to:
Get the price(s) of (.total_item_price) which is inside a cell.
Get the shipping price (.shipping_price) + Add them all up
Display it inside cell (.total_order_price)
Then When I call my delete function, I can call ^this^ function to hopefully update the price correctly.
I also call this getTotalPrice function on DOM Ready to update the prices, so its important it works correctly, It also has to work when I call my delete function (below).
I have a jsfiddle but it doesn't work, but this code does work on my localhost. I had to compact it for jsfiddle, and its broken somewhere. Feel free to edit how you want.
Here Is the Code(!):
This function gets the total price and displays it.
function getTotalPrice(do_request)
{
var prices_array = new Array(); // Where our prices are held
// For each .total_item_price - a <td> within my table.
$(".total_item_price").each(function(e){
var text = $(this).text(); // Get the value
var prices = text.substring(1, text.length); // Format it into a string
prices_array.push(prices); // Push it onto our array
});
var result = eval(0);
// Add up our array
for(i = 0; i < prices_array.length; i++)
{
temp = eval(prices_array[i]);
result += temp;
}
// Round up our result to 2 Decimal Places
result = Math.round(result*100)/100;
// Output/Return our result
if (do_request == null)
{
// We want to add our shipping Price and Display the total
// Get the Shipping Price
var shipping_price = $(".shipping_price").html();
shipping_price = shipping_price.substring(1, shipping_price.length);
// Add em
result += eval(shipping_price);
// Round our result to 2 decimal places
var result=Math.round(result*100)/100;
// Update & Display the Result
$('.total_order_price').html("<b>£" + result + "</b>");
}
else
{
// Otherwise we just want the total price and return it.
return result;
}
}
This is the function I made to delete a row from the table and update the prices.
// Delete Item from Basket, Run on click of delete button
function delete_item(e)
{
doIt = confirm('Delete Item from Basket?\r\n You can not undo this action.');
if(doIt)
{
// Get our basket
var basket_md5 = $(e).parent().find("input[name='basket_md5']").val();
var url = "<?php echo SERVER_URL."shop/basket"; ?>";
// Post to basket
$.post(url, { "do": "delete_item","basket_md5": basket_md5});
// Delete Row from Table
// Row Scope
var row = $(e).parent().parent();
// Effect & Remove from DOM
$(row).fadeOut(1000, function(){
$(this).remove();
});
// Update the Prices (again)
//tprice = getTotalPrice("return");
//$('.total_order_price').html("<b>£" + tprice + "</b>");
getTotalPrice();
}
}
In function delete_item(e) move 'getTotalPrice(); here:
$(row).fadeOut(1000, function(){
$(this).remove();
// Update the Prices (again)
//tprice = getTotalPrice("return");
//$('.total_order_price').html("<b>£" + tprice + "</b>");
getTotalPrice();
});
I have 3 TextFields, called txtUSD, txtEUR, txtAUS. And a PopupList with the same values, minus the txt part, but I need to form the names of the TextFields to use based on the selection that the user made. So I've done this:
function btConvert_Click(event)
{
var amount = document.getElementById("txtAmount").value;
var rates = document.getElementById("lstConvertTo").value;
var from = "txt" + document.getElementById("lstFrom").options[document.getElementById('lstFrom').selectedIndex].text;
var to = "txt" + document.getElementById("lstConvertTo").options[document.getElementById("lstConvertTo").selectedIndex].text;
var curr_from = document.getElementById(from).value;
var curr_to = document.getElementById(to).value;
if(curr_from > curr_to)
{
amount * rates;
} else {
amount / rates;
}
alert(result);
}
But every time I try it I get this error:
mobile/main.js line 215: Result of expression 'document.getElementById(from)' [null] is not an object.
How should I make it?
From the error you're getting, it looks like there's a bug when generating the from variable.
You should consider storing document.getElementById('lstFrom') into it's own var, for brevity.