HTML文本框中的javascript数字

javascript numbers from HTML Textbox

本文关键字:javascript 数字 文本 HTML      更新时间:2023-09-26

我有两个HTML文本框,需要将它们转换为数字,这样我就可以执行计算,但我只是得到NaaN。我的代码是:

其中totalcost是html文本框pg也是一个html文本框

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

我想用"totalcost+pg"填充totalcostbox,因为它是一个点击添加购物车系统。Why Float,它适用于比特币。

试试这个:

// 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

添加了一些注释以帮助解释每个步骤。

让我们这样做:

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()'>

将一元加号运算符与条件一起使用

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