Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to put the coordination generated in Javascript into html form?

I am very new to Javascript. I am trying to put geo coordination directly into html form input field. From w3school, I learned how to generate user latitude and longitude Coordination and now I want to insert them directly into html input field. Here is the code:

var x = document.getElementById("dd");
var y = document.getElementById("da");

function getLocation() {
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(showPosition);
  } else {
    x.innerHTML = "Geolocation is not supported by this browser.";
  }

  function postLocation(x) {
    document.getElementById("ddd").value = x;
  }
}

function showPosition(position) {
  x.innerHTML = "Latitude: " + position.coords.latitude;
  y.innerHTML = "Longitude: " + position.coords.longitude;
}
<html>
<body onload="getLocation()">
  <p>Click the button to get your coordinates.</p>

  <form>
    <label for="fname">First name:</label><br>
    <input type="text" id='' name="fname" value=""><br>
    <label for="lname">Last name:</label><br>
    <input type="text" id="lname" name="lname" value=""><br><br>
    <input type="submit" value="Submit">
  </form>

  <p><strong>Note:</strong> The geolocation property is not supported in IE8 and earlier versions.</p>
  <p id="dd"></p>
  <p id="da"></p>
</body>

</html>

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

add some hidden input to your form like this :

<form>
    <label for="fname">First name:</label><br>
    <input type="text" id='' name="fname" value=""><br>
    <label for="lname">Last name:</label><br>
    <input type="text" id="lname" name="lname" value=""><br><br>
    <input type="hidden" id='lang' name="lang" value="">
    <input type="hidden" id='lat' name="lat" value="">
    <input type="submit" value="Submit">
  </form>

then in your javascript do this :

function showPosition(position) {
  document.getElementById("lat").value = position.coords.latitude;
  document.getElementById("lang").value = position.coords.longitude;
  x.innerHTML = "Latitude: " + position.coords.latitude;
  y.innerHTML = "Longitude: " + position.coords.longitude;
}
    
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading