Soy muy nuevo en Javascript. Estoy tratando de poner la coordinación geográfica directamente en el campo de entrada del formulario html. De w3school, aprendí cómo generar la coordinación de latitud y longitud del usuario y ahora quiero insertarlos directamente en el campo de entrada html. Aquí está el código:
var x = document.getElementById("dd"); var y = document.getElementById("da"); function getLocation() { if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(showPosition); } else { x.innerHTML = "Geolocation is not supported by this browser."; } function postLocation(x) { document.getElementById("ddd").value = x; } } function showPosition(position) { x.innerHTML = "Latitude: " + position.coords.latitude; y.innerHTML = "Longitude: " + position.coords.longitude; }
<html> <body onload="getLocation()"> <p>Click the button to get your coordinates.</p> <form> <label for="fname">First name:</label><br> <input type="text" id='' name="fname" value=""><br> <label for="lname">Last name:</label><br> <input type="text" id="lname" name="lname" value=""><br><br> <input type="submit" value="Submit"> </form> <p><strong>Note:</strong> The geolocation property is not supported in IE8 and earlier versions.</p> <p id="dd"></p> <p id="da"></p> </body> </html>
si desea cambiar el valor de entrada de js, use la propiedad de "valor" de entrada. verifique el fragmento de código:
const input = document.querySelector('input'); const button= document.querySelector('button'); button.addEventListener('click',()=>input.value=Math.random());
<input type="text" placeholder="lat..."/> <button>updateField</button>
agregue alguna entrada oculta a su formulario como este:
<form> <label for="fname">First name:</label><br> <input type="text" id='' name="fname" value=""><br> <label for="lname">Last name:</label><br> <input type="text" id="lname" name="lname" value=""><br><br> <input type="hidden" id='lang' name="lang" value=""> <input type="hidden" id='lat' name="lat" value=""> <input type="submit" value="Submit"> </form>
luego en tu javascript haz esto:
function showPosition(position) { document.getElementById("lat").value = position.coords.latitude; document.getElementById("lang").value = position.coords.longitude; x.innerHTML = "Latitude: " + position.coords.latitude; y.innerHTML = "Longitude: " + position.coords.longitude; }