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());
Related
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
}
I'm trying to add up numbers to the current value. what I am trying to do is almost a simple shopping cart using jQuery.
However, the issue that I am facing is that the numbers wont add up at all. but instead the numbers get replaced by the new one!
And in fact, I get some strange behavior!
To explain this better I've created this FIDDLE
My code is:
$('.addons').click(function() {
var price2 = +$(this).attr('data-price');
$('#fuelcellprice').val(price2);
var inputval = +$('#fuelcellprice').val();
var finaltotal = price2 + inputval;
alert(finaltotal);
});
Could someone please advise on this issue?
If #fuelcellprice stores your sum, set it at the very end of your handler. Don't use +, which is misleading for the purpose. I recommend you to rename your variables to reflect your intent accordingly:
$('.addons').click(function() {
var itemPrice = $(this).attr('data-price');
var currentSum = $('#fuelcellprice').val();
var sum = itemPrice + currentSum;
$('#fuelcellprice').val(sum); //store your final value here
alert(sum);
});
1st you need to use parseFloat()
2nd I don't know why you use $('#fuelcellprice').val() while you set it to price2
try this
var inputval = 0;
$('.addons').click(function() {
var price2 = parseFloat($(this).attr('data-price'));
$('#fuelcellprice').val(price2);
inputval += price2;
alert(inputval);
});
Working Demo
I need to get the number only from an attribute (The number is dynamic). The button/anchor looks like this:
Delete Dish
The part I need to dissect is this bit 'bc_inventorybundle_menu_product_0' I only want the number, for use in another function (Delete a LI with an ID of menuitem0_dish)
The code I use for selecting ID's elsewhere is:
function getNum(element, attrPrefix) {
//set prefix, get number
var prefix = attrPrefix;
var num = element.attr("id").substring((prefix.length));
return num;
}
It works great on ID's but I cant seem to get it to work for Attributes instead of ID's
So User clicks delete button bc_inventorybundle_menu_product_0 then jQuery removes the < li id="menuitem0_dish">
I can't add an ID to the button so I have to use the attribute of the button. As I'm sure you can tell I'm a complete noob when it comes to JS/JQuery.
EDIT
Having read all the answers I feel I may need to elaborate a little.
I think the biggest issue is registering when the Button/Anchor is clicked.
What I currently have is this, which I know must be wrong:
$(document).on('click', 'data("field")', function(event) {
deleteDish(this);
});
function getbutNum(element, attrPrefix) {
//set prefix, get number
var prefix = attrPrefix;
var butnum = element.data("field").substring(prefix.length); //Changed as per suggestions
return butnum;
}
function deleteDish(field) {
var numbut = getbutNum();
//Delete the UL/LI
console.log("Num But" + numbut);
}
Asides from all else this gives me an error of 'unrecognized expression: data("field")'
Have you tried selecting your actual data attribute:
var num = element.attr("data-field").substring(prefix.length);
Or:
var num = element.data("field").substring(prefix.length);
EDIT
First add a class to your anchor element (I'm going under the assumption that you have more than one of these):
Delete Dish
Then:
$(".delete-dish").on("click", function (e) {
e.preventDefault();
var fieldData = $(this).data("field"),
num = fieldData.substring(fieldData.lastIndexOf("_") + 1);
console.log("Num But" + num);
});
Here is a fiddle to demonstrate
Using the attribute name that contains your input should work:
function getNum(element, attrPrefix) {
//set prefix, get number
var prefix = attrPrefix;
var num = element.attr("data-field").substring((prefix.length));
return num;
}
http://jsfiddle.net/zf3hmo4q/
Considering you want to parse attributes with "data-*" name:
function getNum(element, dataName, dataPrefix) {
var num = element.data(dataName).replace(dataPrefix, "");
return num;
}
console.log(getNum($(".btn"), "field", "bc_inventorybundle_menu_product_"));
Maybe something like this?
var getNumberFromAttribute = function(id, field) {
var field = $(id).data(field);
var parts = field.split("_");
return parts[parts.length - 1]
}
Here's a jsfiddle http://jsfiddle.net/o6go79cL/
UPDATE
You could just pass in the element. The only purpose of the id was to select the object. So you could also just do:
var getNumberFromAttribute = function(elm, field) {
var field = $(elm).data(field);
var parts = field.split("_");
return parts[parts.length - 1]
}
number = getNumberFromAttribute(anchorTag, "field");
I have a checkout form where the base price is $249.99. The user has the option to add a desk and or chair for $99.99. As of right now the price changes, but removes the base price instead of adding to it. And upon de-selection, it actually subtracts the base price leaving a total of $0.
$(':checkbox').change(function(){
var sum = 0;
var names = $(':checked').map(function(){
sum += (this.value - 0);
return this.name;
}).get().join(',');
var spans = $('span.amount');
spans[1].innerHTML = sum;
});
I've made a fiddle here to show what I mean. So how do I get the base price to stay $249.99 and do the proper math? Thanks so much for your help in advance.
Why sum = 0 ? Shouldn't it be 249.99 in the given example ?
Take a look at this:
http://jsfiddle.net/XSCZ3/7/
2 issues.
Change your sum to initialize at 249.99.
Last line should change 2 lines of code that show the sum.
http://jsfiddle.net/XSCZ3/12/
Why are you only changing the button price. You should change the button price and the final price heading on the top of the fiddle.
$(':checkbox').change(function(){
var sum = 249.99;
var names = $(':checked').map(function(){
sum += (this.value - 0);
return this.name;
}).get().join(',');
//var spans = $('span.amount'); No need for this
//spans[1].innerHTML = sum; No need for this
$('span.amount').text(sum); //Change to this.
});
Just initialize your sum variable like: var sum = 249.99;
Demo: http://jsfiddle.net/darkajax/vANz4/
I have a table with an id "#stock-hotdogs" where the last column is always of the class ".subtotal". The subtotal is always on this format: $99.00 . So what I need to know is how to get the numbers of all those td's, sum them and store them in a variable. What should be the way to go?
You could do:
var cents_total = 0;
$('#stock-hotdogs .subtotal').each(function() {
var value = $.trim($(this).text());
var parts = value.substr(1).split('.');
cents_total += +parts[0] * 100 + (+parts[1] || 0);
});
I don't use parseFloat here because one should not use float values for financial computations (rounding error). Should be trivial to convert the cent values to dollars :)
var inputs = $('td.subtotal', '#stock-hotdogs').find('input');
var total = 0;
$(inputs).each(function() {
total += parseFloat( $(this).val().replace(/[^\d\.]+/g, ''));
});
Here is a live working example OR
A second version that isn't using input elements...
$('#totalbtn').click(function() {
var total = 0;
$('td.subtotal', '#stock-hotdogs').each(function() {
total += parseFloat( $(this).text().replace(/[^\d\.]+/g, ''));
});
});
HERE is an example for this...
var subTotals = $('#stock-hotdogs td.subtotal');
var sum = 0;
subTotals.each(function() {
sum += parseFloat($(this).text().substr(1));
});
alert(sum);
Working Example: http://jsfiddle.net/FishBasketGordo/f5V9P/
Use:
var total=0;
$('#stock-hotdogs .subtotal').text(function(i,v){
total+=parseFloat(v.substr(1));
});
alert('total: $'+total.toFixed(2));
Take a look at the JQuery Calculation plugin: it lets you specify which fields to sum using jQuery selectors. Using it you would do something like this:
$("#stock-hotdogs").find("td.subtotal").sum();