将 JavaScript 数据结果放入表单输入值


Place JavaScript data result to a form input value

好的,所以我有脚本在onClick之后从地理位置生成纬度和经度。 我现在希望这些坐标放在onClick之后的用户表单值字段中,而不是innerHTML。

我将如何做到这一点? 我还需要使用innerHTML吗?

我的表格详情:

<body>
<h1>Insert New Address</h1>
 <form id="myForm" method="post" action="index3.php">
 <input type="hidden" name="submitted" value="true">
<fieldset>
<legend>New Cafes</legend>
<label>Name<input type="text" name="name"></label>
<label>Address<input type="text" name="address"></label>
<label>Postcode<input type="text" name="address2"></label>
<label>Latitude<input type="text" name="lat" value="" id="addLat"></label>
<label>Longitude<input type="text" name="lng" value="" id="addLng"></label>
</fieldset>
<input type="submit" name="sub" value="Submit">
</form>

<p id="demo">Click the button to get your coordinates:</p>
<button onClick="getLocation()">Try It</button>
<script>
var x=document.getElementById("demo");
function getLocation()
  {
  if (navigator.geolocation)
    {
    navigator.geolocation.getCurrentPosition(showPosition);
    }
  else{x.innerHTML="Geolocation is not supported by this browser.";}
  }
function showPosition(position)
  {
  x.innerHTML="Latitude: " + position.coords.latitude + 
  "<br>Longitude: " + position.coords.longitude;    
  }
</script>

重申一下,我希望生成的纬度和液化天然气结果自动放置在 for 的空"值"字段中,这样用户就不必手动放置在框中。

任何帮助非常感谢:)

获取元素并添加值?

var x = document.getElementById("demo");
function getLocation() {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(showPosition);
    } else {
        x.innerHTML = "Geolocation is not supported by this browser.";
    }
}
function showPosition(position) {
    document.getElementById('addLat').value = position.coords.latitude;
    document.getElementById('addLng').value = position.coords.longitude;
}

小提琴

Basic JavaScript 101

设置表单元素的value,输入没有innerHTML

function showPosition(position) {
    document.getElementById("addLat").value = position.coords.latitude;
    document.getElementById("addLng").value = position.coords.longitude;
}