Skip to content
Advertisement

Number with leading zeroes gets changed in JavaScript

I am calling a javascript function from php using a print statement to print out html code, and I am passing in an integer. However, the value when it is passed in php is not matching the number that the javascript function receives, and I have no clue why.

Here is the php that calls the javascript function:

$upc = $items[$i]->GetUPC();
print "upc: " . $upc . "<br/>";

$delete = "<a href='#' onclick='removeFromCart(". $upc .")' ><img src='".$redx."' height='17' width='17' /></a>";

The print statement prints out the value: 0011110416605

And on the page, using view source, here is the tag for this:

<a href='#' onclick='removeFromCart(0011110416605)' >

Here is the javascript function that is being called:

function removeFromCart(itemID){
    var option = document.getElementById("select_cart");
    var selected = option.options[option.selectedIndex].value;

    alert(itemID);

    loadCart(itemID,selected,"","remove");
}

The alert box is printing out the number: 1226972549

I could understand if it was removing the leading 0’s, but this number is completely different. Does anyone know why this may be?

Advertisement

Answer

JavaScript thinks it is an octal value (because of the leading zero and the lack of digits greater than 7). The decimal value of octal 0011110416605 is 1226972549. Example:

> var value = 010; //10 in octal
> console.log(value);
> 8  //is 8 in decimal

Use a string instead:

removeFromCart("0011110416605")
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement