jagmitg
jagmitg

Reputation: 4546

Javascript Calculation function - Not calculating in html

I am having an issue implementing this calculator on my website which i created. I think i have used the wrong javascript to create the simple calculation which is the following math calculation: ((list price - rrp) / list price) * 100

PLEASE NOTE, i am aware of the values not being numbers, please replace them with any numbers. it still doesnt work.

This is to get the percentage value of the discount against the list and the RRP.

Please review the code before HTML:

 <script type="text/javascript">
   discountFinal(#OriginalPrice, #ListPrice);
 </script>
<div id="discountCode">
   <span id="spanish"></span>
   <span id="spanishtwo">%</span>
</div>

Javascript:

var discountFinal = function (firstly, secondly) {
                var totalfirst = secondly - firstly;
                var totalsecond = totalfirst / secondly;
                var totalthird = totalsecond * 100;
                if (document.getElementById("discountCode").innerHTML === null) {
                    document.getElementById("spanishtwo").innerHTML.replace("%", "")
                } else {
                    document.getElementById("spanish").innerHTML = Math.floor(totalthird / 5) * 5
                }
            };

I dont think i am calling the function within the html properly. Can someone assist with this please.

http://jsfiddle.net/xwzhY/

Upvotes: -1

Views: 435

Answers (3)

Brandon Montgomery
Brandon Montgomery

Reputation: 6986

I'm not sure the error you're getting, but it seems as if you're calling the discountFinal function before it's defined. When you move the call, it starts to work:

http://jsfiddle.net/bmonty/xwzhY/4/

Edit after comment from OP.

You just need to make sure your discountFinal function is defined at the top of your page, before any place it gets called.

This will work:

<script type="text/javascript">
  var discountFinal = function(a, b){};
</script>

<script type="text/javascript">
  var result = discountFinal(1, 2);
</script>

But this will throw an error:

<script type="text/javascript">
  var result = discountFinal(1, 2);
</script>

<script type="text/javascript">
  var discountFinal = function(a, b){};
</script>

To get some clarification, View Source on the HTML page from your browser to see what the resulting page looks like. That should point out where the order of operations is getting messed up.

Upvotes: 2

Paul
Paul

Reputation: 141839

It works fine if you call your function after it exists: http://jsfiddle.net/xwzhY/2/

Just make sure that the function is declared earlier in the code than you use it. Or declare it using a function statement rather than a function expression assigned to a variable:

function discountFinal(firstly, secondly){

...

Upvotes: 1

verbanicm
verbanicm

Reputation: 2526

Trying put "" around your perl variable, you need to pass the value

Upvotes: 0

Related Questions