giliard mei
giliard mei

Reputation: 9

Javascript innerHTML into form text value

I have a javascript code that has an innerhtml function, like this

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

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 + 
    "," + position.coords.longitude;
}
</script>

and I want to enter the output from the javascript code above to be entered into the input text form value

<input type="text" id="gps" name="gps" value="">

but I can't get the results I want, is there a code that I have to add or change?

Upvotes: 0

Views: 46

Answers (1)

creativetim
creativetim

Reputation: 1138

You need to call your function.

Assuming your <script> block is at the bottom of your page, after the <input> has been rendered this should work:

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

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 + 
    "," + position.coords.longitude;
}

getLocation();
</script>

Upvotes: 1

Related Questions