-2

I want to change <p id="demo"></p> to <input type="text" id="demo">

<button onclick="getLocation()">Try It</button>

<p id="demo"></p>

<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>
Stephen Ostermiller
  • 23,933
  • 14
  • 88
  • 109
Dr.GHOST
  • 11
  • 1
  • With a few minor edits, I think this question is now clear with a minimal reproducible example. I expect there is a duplicate somewhere. I can't imagine "how to set the value of an input" hasn't already been asked and answered here. – Stephen Ostermiller Mar 13 '22 at 17:22
  • See also: [How to set value of input text using jQuery](https://stackoverflow.com/questions/10611170/how-to-set-value-of-input-text-using-jquery) which says how to do this using jQuery (whereas this question does not appear to be using jQuery and wants to do it in vanilla JS.) – Stephen Ostermiller Mar 13 '22 at 17:26

1 Answers1

1

Rather than setting x.innerHTML you would set x.value:

<button onclick="getLocation()">Try It</button>

<input type="text" id="demo" />

<script>
var x = document.getElementById("demo");

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

function showPosition(position) {
  x.value = position.coords.latitude + "," + position.coords.longitude;
}
</script>
Stephen Ostermiller
  • 23,933
  • 14
  • 88
  • 109
b4zb0z
  • 105
  • 8