HTML文本框中的javascript数字
javascript numbers from HTML Textbox
我有两个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);
相关文章:
- RegEx JavaScript:数字后的符号提取
- HTML文本框中的javascript数字
- Javascript数字选择器函数
- 我无法让我的javascript数字分类器工作
- 以零结尾的Javascript数字
- Javascript数字放置和如何,4 = 0.04,14 = 0.14,100 = 1.00
- JavaScript 数字近似
- Javascript数字验证功能起作用+需要建设性的批评
- 在小数点后给出一个固定宽度的 JavaScript 数字,同时保留一个数字
- Javascript 数字表示
- Javascript数字变量比较不起作用
- JavaScript 数字继承
- 如何将包含科学记数法的字符串转换为正确的 Javascript 数字格式
- JavaScript:数字计数器实时更新
- Javascript数字到单词 - vigesimal
- Javascript数字到单词 - vigesimal 200-999
- 将 JavaScript 数字转换为小数点后两位
- 带有输入模式的 Javascript 数字和逗号
- 我如何让这个 JavaScript 数字猜谜游戏在没有“while”或“for”循环的情况下工作
- Javascript数字辅助