将javascript弹出结果发送到表单字段

时间:2013-05-02 18:40:17

标签: javascript jquery

我有一个表单,可以捕获您的坐标并发送到服务器以获取邮政编码并返回。

点击获取位置后,您会看到一个弹出字段,我希望结果转到表单字段。

JAVASCRIPT

    function showLocation(position) {
 var latitude = position.coords.latitude;
 var longitude = position.coords.longitude;
  $.getJSON('http://www.uk-postcodes.com/latlng/' + position.coords.latitude + ',' + position.coords.longitude + '.json?callback=?', null, gotpostcode);
}

function errorHandler(err) {
  if(err.code == 1) {
    alert("Error: Access is denied!");
  }else if( err.code == 2) {
    alert("Error: Position is unavailable!");
  }
}


function gotpostcode(result)
{
  var postcode = result.postcode;
    $("#postcodegoeshere").val(postcode);
}

function getLocation(){

   if(navigator.geolocation){
      // timeout at 60000 milliseconds (60 seconds)
      var options = {timeout:60000};
      navigator.geolocation.getCurrentPosition(showLocation, 
                                               errorHandler,
                                               options);
   }else{
      alert("Sorry, browser does not support geolocation!");
   }
}

HTML

  <body>
<form>
     <input type="button" onclick="getLocation();"  
                             value="Get Location"/>

   </form>
   <div>
   <input id='postcodegoeshere' name='xxx' type='text' value='' />
</div>
</body> 

1 个答案:

答案 0 :(得分:1)

您必须使用jQuery选择器。然后,您可以使用.html(postcode)将其放入元素中,或使用.val(postcode)

将其放在输入内(不是复选框,广播或按钮)
function gotpostcode(result)
{
  var postcode = result.postcode;
  $('#postcodegoeshere').html(postcode);
}

有关选择器http://api.jquery.com/category/selectors/的信息,我正在使用此代码中的ID选择器。

更改元素http://api.jquery.com/html/

中的html

更改输入值http://api.jquery.com/val/