You seem to be misunderstanding what you are doing. The flow of your code is all messed up. When you call shopping()
you instruct the browser to tie the keyup event to the apple object. Right after tying it to the object however, you query the variable. But you are simply not fast enough to generate a keyup event between the shopping
function and the keyup
event. Just to show you, instead of logging to the console just that once, try logging it to the console at another time. At any time. Add the following line of code:
$(window).on('click', function(){ console.log(totalcostApple); });
Now you can test when your variable has actually changed. Every time you click, it will log the current value of the totalcostApple
to the console.
But actually, you should improve your code as such:
// add some code to assure that everything you do only gets executed after the DOM is ready
$(document).ready(function(){
// add a default value to your totalcost.
var totalcostApple = 0;
function shopping() {
// remove your keyup event from here and tie it in directly.
var quantity = $("#apple").val();
totalcostApple = (quantity * 0.2).toFixed(2);
// move your log inside the event so you can see it when it *changes*
console.log(totalcostApple);
};
$("#apple").on("keyup", shopping);
});