尝试在if陈述中的输入字段中使用数字时获取NaN [英] Getting NaN when trying to use a number from an input field in an if statment
问题描述
我的部分反思有问题。我试图获取表格单元格以显示需要充电之前还剩下多少英里。
I am having a problem with part of my reflection. I am trying to get table cell to show how many miles are left until charging the car is needed.
我有一个输入单元格,用户可以在其中输入剩余的里程数(50)然后进行计算(50-(10%缓冲区,25)= 25,并显示在它旁边的单元格上。
I have an input cell where the user would type how many miles are left (50) and then a calculation happens (50 - (10% buffer, 25) = 25 and displays on the cell next to it.
我已经遍历了这里可以找到并尝试过的问题
I have gone through the questions on here I can find and tried the approaches others have tried but I really am at a dead end now.
JSFiddle在这里: https://jsfiddle.net/Coxy/gr5bcnsq/
The JSFiddle is here : https://jsfiddle.net/Coxy/gr5bcnsq/
代码为
var car_1_mtnc = document.getElementById('car-1-mtnc');
$(".confirm").click(function() {
var a = parseInt(document.getElementById('car-1-cmra').value, 10);
var miles = a - 25;
if ( a != Number ) {
car_1_mtnc.textContent = "Please enter the miles left";
} else {
car_1_mtnc.textContent = miles;
}
});
HTML
<td><span id="car-1-cmra" class="answer" type="number"></span><input id="car-1-cmr" class="cmr" type="text" value="" placeholder="Enter Miles Left"></input></td>
<td id="car-1-mtnc" class="mtnc"></td>
任何指针都会非常感谢,谢谢您的时间。
Any pointers would be really appreciated, thank you for your time.
推荐答案
您的代码有两个问题。
第一个问题是您得到了 .value 来自
#car-1-crma
的code>使用
The first is that you're getting .value
from #car-1-crma
using
document.getElementById('car-1-cmra').value
但这就是换出 span
因此没有.value-您可以在跨度上使用 .textContent
或使用(now-)隐藏输入
but that's the swap-out span
so doesn't have a .value - you can either use .textContent
on the span or use the (now-)hidden input
document.getElementById('car-1-cmr').value
document.getElementById('car-1-cmra').textContent
$("#car-1-cmra").text()
第二个是您正在使用
if (a != Number)
要在注释中提及,要检查输入是否为数字,请使用
as alluded to in the comments, to check if an input is a number or not, you use
if (isNaN(a))
进行这两个更改可以解决您的麻烦。英里范围计算: https://jsfiddle.net/4m8pa9dh (输入值)和 https://jsfiddle.net/4m8pa9dh/1/ (span textContent)
Making those two changes fixes your fiddle for the miles range calculation: https://jsfiddle.net/4m8pa9dh (input value) and https://jsfiddle.net/4m8pa9dh/1/ (span textContent)
这篇关于尝试在if陈述中的输入字段中使用数字时获取NaN的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!