简体   繁体   中英

How do I add values to input fields using JavaScript?

I'm building a form and would like to automatically fill in the user's coordinates into one of the fields using Google's Geolocation API. I'm only using one input for this because both coordinates are returned together. The text field will be read only so the value cannot be changed by the user. The code I have so far isn't working.... Any suggestions?

The code:

<input type="text" id="cor" readonly placeholder="coordinates">
<input class="ra26" type="button" value="View Coordinates" Onclick="getLocation()">
<script> var x = document.getElementById("cor");
function getLocation() {
   if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(showPosition, showError);
   } else {
      x.innerHTML = "Geolocation is not supported by this browser.";
   }
}

function showPosition(position) {
    x.innerHTML = "Lat: " + position.coords.latitude +
     "<br>Lon: " + position.coords.longitude;
}

 function showError(error) {
    switch (error.code) {
       case error.PERMISSION_DENIED:
           x.innerHTML = "User denied the request for Geolocation."
           break;
       case error.POSITION_UNAVAILABLE:
           x.innerHTML = "Location information is unavailable."
           break;
       case error.TIMEOUT:
           x.innerHTML = "The request to get user location timed out."
           break;
       case error.UNKNOWN_ERROR:
           x.innerHTML = "An unknown error occurred."
           break;
    }
 }
 </script>

an input field doesn't have an innerHTML property.

change all occurrences of innerHTML to value like so:

x.value= "Geolocation is not supported...";

for reference: http://www.w3schools.com/jsref/prop_text_value.asp

you could, on the other hand, display it in a div or ap tag like so:

<div id="cordiv"></div>
<script>

var x = document.getElementById("cordiv");
function getLocation() {
   if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(showPosition, showError);
   } else {
      // now x refer's to a div-element, so you can make use of the innerHTML-Property:
      x.innerHTML = "Geolocation is not supported by this browser.";
   }
 }

 // ...rest of your code here

</script>
  1. Try

if (typeof navigator.geolocation != 'undefined')

2.

showPosition(), showError() needs a parameter

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM