Jonny Jordan
Jonny Jordan

Reputation: 407

how to not return nan from answer jquery

I've just started learning jquery and I was trying to figure out how to get rid of NAN when there is a space or a letter etc. and change it to nothing? Also is there a better way to write what i've done?

Jquery:

$(document).ready(function(){
    var one = 9; 
    var two = 7;

    $('#first').keyup(function(){ 
        var firstValue = parseFloat($('#first').val()); 
        $('#second').val(firstValue * one / two);
    });

    $('#second').keyup(function(){ 
        var secondValue = parseFloat($('#second').val()); 
        $('#first').val(secondValue / two * one);
    });
});

HTML:

<input id=first></input> <input id=second></input>

Upvotes: 0

Views: 163

Answers (3)

emerson.marini
emerson.marini

Reputation: 9348

First, fix your HTML markup:

<input type="text" id="first" />
<input type="text" id="second" />

Then, you can do it as recommended by @Barman:

$(document).ready(function(){
    var one = 9; 
    var two = 7;

    $('#first').on('keyup', function(){ 
        var firstValue = parseFloat($('#first').val());

        if (!isNaN(firstValue)) {
            $('#second').val(firstValue * one / two);
        }
    });

    $('#second').on('keyup', function(){ 
        var secondValue = parseFloat($('#second').val()); 

        if (!isNaN(secondValue)) {            
            $('#first').val(secondValue / two * one);
        }
    });
});

Demo

Number.isNaN()

Upvotes: 0

Kartikeya Khosla
Kartikeya Khosla

Reputation: 18873

$(document).ready(function(){
var one = 9; 
var two = 7;

$('#first').keyup(function(){ 
    var firstValue = parseFloat($('#first').val()); 
    if(!isNaN(firstValue))         // Use 'isNaN' as shown
    $('#second').val(firstValue * one / two);
});

$('#second').keyup(function(){ 
    var secondValue = parseFloat($('#second').val()); 
    if(!isNaN(secondValue))        // Use 'isNaN' as shown
    $('#first').val(secondValue / two * one);
});
});

Read More here :- http://www.w3schools.com/jsref/jsref_isnan.asp

Upvotes: 0

Barmar
Barmar

Reputation: 780818

Use isNaN() to test the value before using it.

$('#first').keyup(function(){ 
    var firstValue = parseFloat($('#first').val());
    if (!isNan(firstValue) {
        $('#second').val(firstValue * one / two);
    }
});

Upvotes: 2

Related Questions