Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Division produces NaN

I'm trying to divide the variable number by 100 and get NaN. I'm new to jQuery, can anyone help me to understand what I'm doing wrong?

$.each(data.products, function (i, data) {

    var div_data = "<p>" + data.title + "<br/>" + data.description + "</p>";

    div_data += '<img src="' + data.imageUrl + '" title="Loading..." alt="Loading...">';
    div_data += '<p><a href="' + data.url + '">Buy</a></p>';

    $(div_data).appendTo("#testjson");

    number = '<div class="number">' + data.price + '</div>';
    $('#myElement').text((number / 100));

});
like image 727
leanda Avatar asked Oct 24 '25 17:10

leanda


2 Answers

First you're setting number to a string:

number = '<div class="number">'+ data.price + '</div>';

Then you are dividing that string by 100

In JavaScript that results in NaN which is short for Not a Number . This is specified in the spec.

A possible solution could be to divide the number itself by 100, and not the HTML string, for example:

var number = data.price/100;
$('#myElement').text(number);

This would not attach a nested div to your #myElement though.

like image 50
Benjamin Gruenbaum Avatar answered Oct 26 '25 06:10

Benjamin Gruenbaum


You can do it like this

    number = '<div class="number">' + (data.price/100) + '</div>';
    $('#myElement').text((number ));

This is what you are doing in .text()

('<div class="number">' + (data.price/100) + '</div>')/100
like image 36
Kimtho6 Avatar answered Oct 26 '25 05:10

Kimtho6