James Bailey James Bailey - 7 months ago 20
Javascript Question

getElementById is not being updated

My JS :



function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position){
document.getElementById("xc").value = position.coords.latitude;
document.getElementById("yc").value = position.coords.longitude;
document.getElementById("loginform").submit;
});
} else {
document.getElementById("xc").value = '0';
document.getElementById("yc").value = '0';
document.getElementById("loginform").submit;
}
}


My HTML :



<form id="loginform" action="./functions/dologin.php" method="post">
<input type="hidden" id="xc" name="xc" value="X">
<input type="hidden" id="yc" name="yc" value="X">
<input class="myButton" type="submit" onclick="getLocation();" value="Login">
</form>


I've tried everything, from an
onsubmit="return getlocation();"
in the form - with button type submit, to jQuery to DOM

The value is always "X".

Answer

Your form is getting submitted which is just causing the page to get reloaded which makes the changes you just made to the page get overwritten by the newly loaded page.

So, this is what it does:

  1. Click button
  2. Your Javascript code runs that modifies the page
  3. Form gets submittted
  4. Page gets reloaded - all your changes you just make to the page disappear

If you add a return false; to the end of your getLocation() and then return that in the HTML, it should stop the form from getting submitted.

function getLocation() {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(function(position){
            document.getElementById("xc").value = position.coords.latitude;
            document.getElementById("yc").value = position.coords.longitude;                                                    
            document.getElementById("loginform").submit;
        });     
    } else {
        document.getElementById("xc").value = '0';
        document.getElementById("yc").value = '0';
        document.getElementById("loginform").submit;
    }
    // prevent default submit of the form
    return false;
}

<form id="loginform" action="./functions/dologin.php" method="post">
    <input type="hidden" id="xc" name="xc" value="X">
    <input type="hidden" id="yc" name="yc" value="X">
    <input class="myButton" type="submit" onclick="return getLocation();" value="Login">               
</form>

You could also change your button to just be a regular button, not a submit button and then there would be no default submit of the form.

<form id="loginform" action="./functions/dologin.php" method="post">
    <input type="hidden" id="xc" name="xc" value="X">
    <input type="hidden" id="yc" name="yc" value="X">
    <button class="myButton" onclick="getLocation();">Login</button>               
</form>