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

Time:04-04

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 onl oad="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>

CodePudding user response:

if you want to change the input value from js use the input "value" property. check the code snippet:

const input = document.querySelector('input');
const button= document.querySelector('button');

button.addEventListener('click',()=>input.value=Math.random());
<input type="text" placeholder="lat..."/>
<button>updateField</button>

CodePudding user response:

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