I normally use the following code to get PHP variables into JavaScript:
echo("var zipCode = " . $zipCode . ";");
This works fine but on zip codes that start with a 0 it is truncating it.
I am trying to figure out a way to keep the leading 0.
Any help would be great.
Thanks
Make it a string then:
echo("var zipCode = '" . $zipCode . "';");
Notice the two ' characters before and after the concatenating of $zipCode.
I'm sure $zipCode is a string in your PHP, but when you echo it, it doesn't include the quotes. That means your resulting Javascript would look like:
var zipCode = 01234;
And there's no reason to store it as a number (incorrect number, in this case, since it will think it's an octal number).
So by adding the ' characters, the resulting Javascript becomes:
var zipCode = '01234';
And should be just fine with manipulating, since you should really only be doing string manipulations on a zip code anyways.
If, for whatever reason, you decide that you need the Number form of the zip code, you can use this in Javascript:
var zipCodeNum = parseInt(zipCode, 10);
The important part is the , 10, as this will force the conversion to be in base 10, ignoring any leading 0s.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With