0

I have 2 HTML textboxes and need to convert them to numbers so I can perform a calculation but I am just getting NaaN. My code is:

Where totalcost is html textbox and pg is also a html textbox

document.getElementById("totalcost").value = parseFloat(document.getElementById("pg").value) + parseFloat(document.getElementById("totalcost").value);

I want the totalcost box to be populated by "totalcost + pg" as it is a click and add cart system. Why Float, its for bitcoin.

user3774914
  • 29
  • 1
  • 5

3 Answers3

0

Try this:

// get the `pg` value and attempt to convert to a Number, otherwise default to 0.00
var pg = Number(document.getElementById("pg").value) || 0.00; 

// get the `totalcost` value and attempt to convert to a Number, otherwise default to 0.00
var totalCost = Number(document.getElementById("totalcost").value) || 0.00;

// update the `totalcost` element to include the sum of `pg` and `totalcost`
document.getElementById("totalcost").value = pg + totalCost

Added some comments to help explain each step.

smaili
  • 1,245
  • 9
  • 18
0

Lets do that:

function isNumeric(n) {
  
  /* http://stackoverflow.com/a/1830844/603774 */
  
  return !isNaN(parseFloat(n)) && isFinite(n);
}

function calc() {

  var
    d_1 = document.getElementById('d_1').value,
    d_2 = document.getElementById('d_2').value,
    result;
  
  /* Validation for d_1 */
  if (!isNumeric(d_1)) {
    
    alert('d_1 is not a number');
    
    return;
  }
  
  /* Validation for d_2 */
  if (!isNumeric(d_2)) {
    
    alert('d_2 is not a number');
    
    return;
  }
  
  result = +d_1 + +d_2;
  
  alert('Result: ' + result);
}
<input type="text" id="d_1"> + <input type="text" id="d_2"> <input type="button" value="calculate" onclick='calc()'>
Ali Mamedov
  • 5,116
  • 3
  • 33
  • 47
0

Use the unary plus operator with or conditional

document.getElementById("totalcost").value = (+(document.getElementById("pg").value) || 0) + (+(document.getElementById("totalcost").value) || 0);
Shreevardhan
  • 12,233
  • 3
  • 36
  • 50