简体   繁体   中英

Why am I getting an NaN value?

My jQuery is:

$("#listDB").on("change", ".qfStyle", function(event) {
    var id = $(this).parents("tr").find('.itemCbox').val();
    $qnty = $("#qnty"+id);
    $unit = $("#unit"+id);
    $price = $("#price"+id);

    if($(this).parents("tr").find('.pbo').text()=="Kilos")
    {
        if(this.value<1)
        {
            $qnty.text(this.value*1000);
            $unit.text("gm");

            var data = "action=getPrice&id="+id;
            $.post("addBill.php", data, function(json) {
                alert(json.price);
                $price.text(json.price*this.value);
            }, 'json');
        }
    }
});

The JSON data returned by the server is:

{"price":"52.00"}

Here, this refers to a textbox. I'm getting the value NaN for the expression:

$price.text(json.price*this.value);

But I've ensured that both this.value and json.price are both numbers. So, why do I get NaN when I multiply them?

The problem is that this isn't in a scope of a post function.

Check the code below. I added a new variable value which holds the value of this.value and which should be available even in a post function.

$("#listDB").on("change", ".qfStyle", function(event) {
    var id = $(this).parents("tr").find('.itemCbox').val();
    $qnty = $("#qnty"+id);
    $unit = $("#unit"+id);
    $price = $("#price"+id);

    var value = this.value;

    if($(this).parents("tr").find('.pbo').text()=="Kilos")
    {
        if(value<1)
        {
            $qnty.text(value*1000);
            $unit.text("gm");

            var data = "action=getPrice&id="+id;
            $.post("addBill.php", data, function(json) {
                alert(json.price);
                $price.text(json.price*value);
            }, 'json');
        }
    }
});

You can use Number() to extract a string number to number format.

 function getStringNumber(stringNumber){ var formatNumber = Number(stringNumber); console.log(formatNumber); } 
 <html> <button onclick="getStringNumber('24.00')"> Convert String Number </button> </html> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM