简体   繁体   中英

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?

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM