Dragan Subasic Dragan Subasic - 2 months ago 9
jQuery Question

NaN error when multiplying

I have this script to multiply two columns and display total in third. Here it is code:

<script>
$(function() {
$("#num1, #num2").on("keydown keyup", sum);
function sum() {
$("#total").val(Number($("#num1").val()) * Number($("#num2").val()));
}
});
</script>


And form:

<form method="POST" name="form1" action="" ">

<label>num1</label>
<input name="num1" id="num1" type="text" value="SOMENUMBER" />

<label>num2</label>
<input type="text" name="num2" id="num2" value="SOMENUMBER"/>

<label>total</label>
<input type="text" name="total" style="width: 40%;" id="total" readonly />

<button class="square" name="btn" type="submit">SOMEBUTTONNAME</button>

</form>

Answer

You have 3x " in HTML: action="" ".

This code prevents from not-numeric characters and calculate result on click button or change some number.

function sum() {
  var num1 = $("#num1").val().replace(",",".");
  var num2 = $("#num2").val().replace(",",".");
  var decimals_prepare = (num1.indexOf(".") > -1) ? num1.split(".")[1].length : 0;
  
  return (!isNaN(num1) && !isNaN(num2)) ? $("#total").val((num1 * num2).toFixed(decimals_prepare)) : console.log("false");
}

$(function() {
  $("#num1, #num2").on("keydown keyup", sum);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="POST" name="form1" action="">

  <label>num1</label>
  <input name="num1" id="num1" type="text" value="5" />

  <label>num2</label>
  <input type="text" name="num2" id="num2" value="2" />

  <label>total</label>
  <input type="text" name="total" style="width: 40%;" id="total" readonly />

  <button class="square" name="btn" type="submit" onclick="sum()">SOMEBUTTONNAME</button>

</form>