luissimo luissimo - 6 months ago 10
jQuery Question

Why doesn't Javascript put some respeck on my input value?

I'm currently working on a budget software and I've come across this strange bug. First of here is my code:

<label class="label label-success">Choose your budget</label><br/><br/>

<div class="input-group-addon">€</div>
<input type="number" min="10" max="25000" maxlength="5" step="10" class="form-control" id="Input-budget" placeholder="Amount" onkeyup="this.value=this.value.replace(/[^\d]/,'')" onchange="budCalculate(this.value)">


this is the output line:

<li>
<strong>
Total cost: <span id="cost_eur">€0.00 </span> (<span id="cost_usd" class="small">$0.00</span>)
</strong>
</li>


Here is the Javascript:

function budCalculate(budget_amount) {
var budget = budget_amount;
cost_eur.innerHTML = "€"+((budget).toFixed(2);
cost_usd.innerHTML = "$"+ (budget * 1.13 ).toFixed(2);
}


It's supposed to put the value of the input on the output line.

The
onkeyup
is to prevent people from typing letters.

I've tried all kinds of variations and the funny thing is almost the same identical code is working on a similar looking page.

Why doesn't JavaScript put respeck on my value?

Answer

I suspect the issue is that budget is not a Number Object. this.value will pass a String Object. I would advise changing your function:

function budCalculate(budget_amount) {
  var budget = 0;
  console.log(typeof budget_amount);
  budget = parseFloat(budget_amount);
  cost_eur.innerHTML = "€" + budget.toFixed(2);
  cost_usd.innerHTML = "$" + ( budget * 1.13 ).toFixed(2);
  return budget;
}

You can now see what type of object is being passed. The parseFloat() should correct the issue.