Dazvolt
Dazvolt

Reputation: 697

Get value from input, result as NaN

This is weird, I'm trying to make a simple calculation, but I'm not able to get value from inputs for some reason, and it's working for only specific inputs, not for everyone.

This is the way I'm trying to get value:

var Days = parseInt($('#days').val());
var DaysPayment = parseInt($('#days-payment').val());

But it's not working, though other inputs is working fine.

You can see this on JSFiddle here: http://jsfiddle.net/jEU4L/

Upvotes: 1

Views: 341

Answers (2)

K.K.Agarwal
K.K.Agarwal

Reputation: 856

You need to change your function :

$(document).ready(function(){
    var Payment = parseInt($('#payment').val().replace(/ /g,""));

    var Execute = $('#execute');
    var Total = $('#total');
    var TotalNDS = $('#total-nds');

    Execute.on('click',function(){

        var NDS = 0
    var Days = 0
    var DaysPayment= 0
    if($('#nds') > 0)
     NDS = parseInt($('#nds').val());
    if($('#days') > 0)
     Days = parseInt($('#days').val());
    if($('#days-payment') > 0)
     DaysPayment = parseInt($('#days-payment').val());

        console.log(Days+' '+DaysPayment);
        var t1 = Payment/100;
        console.log(t1);        
        var t2 = t1 * NDS;
        console.log(t2);
        var t3 = Payment - t2;
        console.log(t3);
        var t4 = t3 / Days;
        console.log(t4);
        var t5 = t4 * DaysPayment;
        console.log(t5);

        Total.val(t5);


    });

});

Because you are not getting the default value in Days or days in month varables so you are getting NaN

Upvotes: 0

Rory McCrossan
Rory McCrossan

Reputation: 337570

You need to retrieve the values from those fields within the click handler. At the moment you are getting them on load when they are blank, hence the calculation yields NaN. Also, you should include the radix on parseInt calls. Try this:

$(document).ready(function () {
    var $execute = $('#execute');
    var $total = $('#total');
    var $totalNDS = $('#total-nds');

    $execute.on('click', function () {
        var payment = parseInt($('#payment').val().replace(/ /g, ""), 10);
        var nds = parseInt($('#nds').val(), 10);
        var days = parseInt($('#days').val(), 10);
        var daysPayment = parseInt($('#days-payment').val(), 10);

        var t1 = payment / 100;
        var t2 = t1 * nds;
        var t3 = payment - t2;
        var t4 = t3 / days;
        var t5 = t4 * daysPayment;    
        $total.val(t5);
    });
});

Updated fiddle

I also changed the variable names to use the usual JS and jQuery conventions (ie. variables containing jQuery objects are prefixed with a $ and variable names should be camel-cased).

Upvotes: 3

Related Questions