Reputation: 3093
I'm trying to obtain the users location, then insert into two seperate <input>
fields. The script works when trying to print to, <p id="lat"></p>
. But not for the <input>
.
<form>
<input type="number" step="any" name="lat" id="lat" value="" />
<input type="number" step="any" name="lng" id="lng" value="" />
</form>
<button onclick="getLocation()">Get current location</button>
<script>
var x = document.getElementById("lat").value;
var y = document.getElementById("lng").value;
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
function showPosition(position) {
x.innerHTML = position.coords.latitude;
y.innerHTML = position.coords.longitude;
}
</script>
What am I missing here? Have added .value
to the end of the veriable, am wondering if its the data
type and/or step
values?
Upvotes: 2
Views: 2947
Reputation: 15715
just set x.value= position.coords.latitude;
and remove initialize
x= document.getElementById("lat");
var x = document.getElementById("lat");
var y = document.getElementById("lng");
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
function showPosition(position) {
x.value= position.coords.latitude;
y.value= position.coords.longitude;
}
Upvotes: 1
Reputation: 128781
x
doesn't have an innerHTML
because x
is equal to the string value held within your #lng
element. It isn't equal to the element itself.
Rather than setting x
and y
to the value
of each of your elements, set them to your elements themselves:
var x = document.getElementById("lat");
var y = document.getElementById("lng");
Then you can set the value using x.value
and y.value
(x.innerHTML
or y.innerHTML
):
x.value = "Geolocation is not supported by this browser.";
And:
function showPosition(position) {
x.value = position.coords.latitude;
y.value = position.coords.longitude;
}
Upvotes: 3