Number with leading zeroes gets changed in JavaScript

后端 未结 4 1513
既然无缘
既然无缘 2020-12-06 21:57

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 no

相关标签:
4条回答
  • 2020-12-06 22:46

    Solve it by creating a hidden text called it 'tempcart' then assing value to it with HTML or PHP, it will keep the leading zeros intact as a text string. To make sure, convert it to string if you are passing it thru PHP

    HTML:

    <input type='hidden' id='tempcart' value='0011110416605'>
    

    PHP:

    $itemID = '0011110416605';
    $itemID = strval( $itemID );
    echo "<input type='hidden' id='tempcart' value=$itemID >";
    

    SCRIPT:

    function removeFromCart() {
    var itemID = document.getElementById('tempcart').value;
    alert(itemID);
    //do whatever...
    }
    

    This is just sample programming, you need to fit it in your program. I guess Javascript can't pass due to convertion to octal value (because of the leading zero and the lack of digits greater than 7) as @Vivid mention before.

    0 讨论(0)
  • 2020-12-06 22:51

    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")
    
    0 讨论(0)
  • 2020-12-06 22:54

    I found this issue and I fixed it by using parseInt:

    itemID = parseInt('0011110416605',10);
    
    0 讨论(0)
  • 2020-12-06 22:58

    You can just call with including '' quotes

    Like onchange="updateLineTotal{$id,'{$po101}')";

    Just include it in quotes so it will consider it as string not an integer

    0 讨论(0)
提交回复
热议问题