MangoPie MangoPie - 1 year ago 81
Javascript Question

Can't get isNaN function to work properly

I've created three text boxes. The first two text boxes are for two numbers (for subtraction). The result will appear in the third text box. I'm trying to make it so that if the user puts in a letter instead of a number, an alert happens.

Right now, the isNaN isn't working. Whenever I put anything in the first or second textbox, it alerts, regardless of number or letter. Here's my code.

function myFunction() {
var x = document.getElementById("taxFree"); //textbox 1
var y = document.getElementById("prodCost"); //textbox 2
var res = document.getElementById("salesMargin"); //Result textbox

// If x or y is Not a Number, send alert to user
if (isNaN(x) || isNaN(y)) {
alert("Numers only!");
res.value = x.value - y.value;

Thanks in advance!

Answer Source

Try checking the value of the input:

if (isNaN(x.value) || isNaN(y.value)) {
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download