繁体   English   中英

如何使用JavaScript向输入字段添加值?

[英]How do I add values to input fields using JavaScript?

我正在构建一个表单,并希望使用Google的Geolocation API将用户的坐标自动填写到其中一个字段中。 我只使用一个输入,因为两个坐标一起返回。 文本字段将是只读的,因此用户无法更改该值。 到目前为止,我的代码无法正常工作。...有什么建议吗?

编码:

<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>

输入字段没有innerHTML属性。

将所有出现的innerHTML更改为value如下所示:

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

供参考: http : //www.w3schools.com/jsref/prop_text_value.asp

另一方面,您可以将其显示在div或ap标签中,如下所示:

<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. 尝试

如果(typeof navigator.geolocation!='undefined')

2。

showPosition(),showError()需要一个参数

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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