Javascript Phone Number Autocomplete
Hi is there anyway using Javascript to get user's current location and autocom开发者_运维知识库plete fields in a form like telephone country code (e.g. in Singapore it is +65) and area code?
It's really difficult, and I'd advise against it because it's loads of effort for very little reward. The best way (most fluid for the user) would be to get the users IP using PHP/ASP/Ruby-on-Rails/whatever and query one of the freely available Geo-IP databases (Google it) to match that to a country, then create your own database of country codes (using this, or similar).
If you really really want to do it using JavaScript, it'll only let you do it in newer browsers, and it'll prompt the user that you want to know their location... a lot of people will wonder why you're asking for this and click no.
// first, check it's supported
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(insertCountryCode);
}
insertCountryCode
is a function that you pass. Why? Because the prompt for the user to allow your website to know their location is non-modal, meaning the page will carry on running while it waits for a response, so the function when they do respond will be asynchronous (outside the normal flow). This function is where you look up their location and insert their country code. In this function, use the Google Maps API and pass the latlng parameter to get the country... then you need to find another lookup service which will let you find out the dialing code.
The reason I've explained this is to show you how hard it is. A much simpler alternative would be to have a drop-down box with
<option value="+65">Singapore</option>
and insert the value into the phone number box. That's what I advise you do.
精彩评论