0

If I'm using the following code to make a calculation and assign it to a variable, how would I go about making that variable accessible anywhere on the html page? I thought that simply declaring it as result from elsewhere on the page = (quantity * product).toFixed(2) ;would then allow me to output it to the console using console.log('result from elsewhere on the page is p * q ' + result); but when I do that I get result from elsewhere on the page is p * q [object HTMLSpanElement] as the output

<script>
$('#quantity,#product').bind('change keyup', function () {
  var product = $('#product').val(),
      quantity = parseInt($('#quantity').val(), 10),
      result = (quantity * product).toFixed(2);
  $('#result').text(result);
  console.log('Testing console');
  console.log('result is p * q ' + result);
  console.log('quantity is ' + quantity);
});

</script>   

note: the first output console.log('result is p * q ' + result); works fine and outputs result is p * q 98.00 it's only when I try it from outside of the that I get the result from elsewhere on the page is p * q [object HTMLSpanElement] returned.

thanks for any help with this.

1
  • Let's see the code you're using elsewhere on the page as well? Commented Dec 17, 2013 at 12:21

2 Answers 2

1

Use window.result or window["result"] notations.

EDIT: I assumed that u haven't changed the result somewhere else.

Sign up to request clarification or add additional context in comments.

Comments

1

You have a variable declaration for result there.

var ...., result = (quantity * product).toFixed(2);

When you declare a variable like that it gets declared in the scope of the current function (or the global scope if performing it outside of all functions).

Instead, declare it in the outside scope and just use it:

var result;
$('#quantity,#product').bind('change keyup', function () {
  var product = $('#product').val(),
      quantity = parseInt($('#quantity').val(), 10);

  result = (quantity * product).toFixed(2);
  $('#result').text(result);
  console.log('Testing console');
  console.log('result is p * q ' + result);
  console.log('quantity is ' + quantity);
});
//result is now available here, 
// (but equal to undefined until someone will trigger the event)

Note that since you get "result from elsewhere on the page is p * q [object HTMLSpanElement]" chances are you already have a result variable in that scope. Make sure you don't or give it another name.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.