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

时间:2013-10-03 13:53:27

标签: javascript php html forms

好的,所以我有一个脚本,可以在onClick之后从地理位置生成纬度和经度。我现在希望在onClick之后将这些坐标放在users表单值字段中,而不是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>

重申一下,我希望生成的lat和lng结果自动放入for中的空“值”字段中,这样用户就不必手动放在框中。

非常感谢任何帮助:)

2 个答案:

答案 0 :(得分:0)

基本JavaScript 101

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

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

答案 1 :(得分:0)

获取元素并添加值?

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

FIDDLE