I am new to HTML, CSS, and JavaScript, so please bear with me.
I am trying to create a form which has an element that uses geolocation to get the current location of a user when user checks a checkbox, and it inputs the coordinates inside a textbox that I've set up. This works fine, but when I uncheck the checkbox, the coordinates disappear along with the textbox.
How do I clear just the coordinates without making the textbox disappear as well?
Below is my code:
function getLocation(myCheck) {
var x = document.getElementById("place");
if (myCheck.checked) {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
x.innerHTML = "Geolocation disabled or unavailable.";
}
function showPosition(position) {
x.innerHTML = position.coords.latitude + ", " + position.coords.longitude;
}
} else {
x.innerHTML = "";
}
}
<h4> Coordinates: <label id="place"><input type="text"></label><label>Use current location? <input id="myCheck" onclick="getLocation(this)" type="checkbox"></label>
</h4>
To empty an input you need to set the value instead of innerHTML. Also note you can avoid creating an input inside the label tag by just using the id & for attribute
function getLocation(myCheck) {
var x = document.getElementById("place");
if (myCheck.checked) {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
x.value = "Geolocation disabled or unavailable.";
}
} else {
x.value = "";
}
}
function showPosition(position) {
x.innerHTML = position.coords.latitude + ", " + position.coords.longitude;
}
<h4> Coordinates: <label for="place">
<input id ="place" type="text"></label>
<label for="myCheck">Use current location?
<input id="myCheck" onclick="getLocation(this)" type="checkbox">
</label>
</h4>
Could you try?
document.getElementById('myCheck').value = "";
Related
I have a Google places auto completion search bar. The post data from the form is read in Symfony. The search bar works fine but the user has to click on a place in the list, so I made it that if the user hits enter it'd simulate a down arrow and select the first suggestion.
If a user clicks on a place in the list I do a jQuery form.append to add the lat/lng
If a user hits enter I can see the form.append happening in inspect elements but the fields are not showing up in the post data.
Below is the code that handles the auto completion and simulated down arrow
window.autocomplete = null;
const form = $('#search-form');
function initAutocomplete() {
var pac_input = document.getElementById('search-input');
(function pacSelectFirst(input) {
// store the original event binding function
var _addEventListener = (input.addEventListener) ? input.addEventListener : input.attachEvent;
function addEventListenerWrapper(type, listener) {
// Simulate a 'down arrow' keypress on hitting 'return' when no pac suggestion is selected,
// and then trigger the original listener.
if (type === "keydown") {
var orig_listener = listener;
listener = function (event) {
var suggestion_selected = $(".pac-item-selected").length > 0;
if (event.which === 13 && !suggestion_selected) {
var simulated_downarrow = $.Event("keydown", {
keyCode: 40,
which: 40
});
orig_listener.apply(input, [simulated_downarrow]);
}
orig_listener.apply(input, [event]);
};
}
_addEventListener.apply(input, [type, listener]);
}
input.addEventListener = addEventListenerWrapper;
input.attachEvent = addEventListenerWrapper;
// Create the autocomplete object, restricting the search to geographical location types.
autocomplete = new google.maps.places.Autocomplete(input,
{types: ['geocode']});
autocomplete.addListener('place_changed', fillInAddress);
})(pac_input);
}
Below is the function fillInAddress which adds the fields.
function fillInAddress() {
let place = autocomplete.getPlace();
console.log(place)
let lat = place.geometry.location.lat();
let lng = place.geometry.location.lng();
let searchplace = place.formatted_address;
let searchplaceElement = $('#searchplace');
if (!searchplaceElement.length) {
form.append("<input id='searchplace' name='searchplace' type='hidden' value='" + searchplace + "'>")
form.append("<input id='lat' name='lat' type='hidden' value='" + lat + "'>")
form.append("<input id='lng' name='lng' type='hidden' value='" + lng + "'>")
} else {
searchplaceElement.val(searchplace);
$('#lat').val(lat);
$('#lng').val(lng);
}
}
Below is the HTML form part.
<form action="/restaurants" id="search-form" method="post">
<div class="input-group input-group-lg">
<div class="input-group-prepend">
<span class="input-group-text"><i class="fa fa-map-marker"></i></span>
</div>
<input id="search-input" class="form-control shadow-none" type="text" placeholder="Zoeken op adres of postcode">
<div class="input-group-append">
<button type="submit" class="btn btn-dark">Zoeken</button>
</div>
</div>
</form>
I have to add I'm not a real good export on jQuery or Javascript.
The standard submit button only submits form fields that were initially loaded. Fields that were added after DOM loads, have to get submitted manually for example like this:
$('#search-form).on('submit', function(e) {
e.preventDefault();
$.post($(this).attr('action'), $(this).serialize());
});
I'm trying to auto fill the data in input field which is shown in <div id="demo"></div>. How do I go about doing it?
I tried this but it's not working:
<input id="demo" type="text" />
DEMO: https://jsfiddle.net/z6m3824c/
HTML
<div id="demo"></div>
JS:
var x=document.getElementById("demo");
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()
input field has value.
Try this:
<input id="demo" type="text" onLoad="" />
var x=document.getElementById("demo");
function getLocation()
{
if (navigator.geolocation)
{
navigator.geolocation.getCurrentPosition(showPosition);
}
else{x.value="Geolocation is not supported by this browser.";}
}
function showPosition(position)
{
x.value="" + position.coords.latitude +
", " + position.coords.longitude;
}
getLocation()
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 5 years ago.
There's a form on my webpage which is supposed to get the address of the user in a formfield.
When the user clicks allow on the location prompt my purpose is to get the address of the user in an input box in the form.
The prompt comes but this code is unable to fetch the address of the user.
I am looking for something like this
Here's my code
HTML
<form id="contact" action="" method="post" align="center">
<fieldset>
<input placeholder="Your Address" id="address" type="text" tabindex="1" required autofocus>
</fieldset>
<fieldset>
<button name="submit" type="submit" id="contact-submit" data-submit="...Sending">Submit</button>
</fieldset>
Javascript
<script src="https://code.jquery.com/jquery-1.10.1.js"></script>
<script>
$(document).ready(function () {
var currgeocoder;
//Set geo location lat and long
navigator.geolocation.getCurrentPosition(function (position, html5Error) {
geo_loc = processGeolocationResult(position);
currLatLong = geo_loc.split(",");
initializeCurrent(currLatLong[0], currLatLong[1]);
});
//Get geo location result
function processGeolocationResult(position) {
html5Lat = position.coords.latitude; //Get latitude
html5Lon = position.coords.longitude; //Get longitude
html5TimeStamp = position.timestamp; //Get timestamp
html5Accuracy = position.coords.accuracy; //Get accuracy in meters
return (html5Lat).toFixed(8) + ", " + (html5Lon).toFixed(8);
}
//Check value is present or
function initializeCurrent(latcurr, longcurr) {
currgeocoder = new google.maps.Geocoder();
console.log(latcurr + "-- ######## --" + longcurr);
if (latcurr != '' && longcurr != '') {
//call google api function
var myLatlng = new google.maps.LatLng(latcurr, longcurr);
return getCurrentAddress(myLatlng);
}
}
//Get current address
function getCurrentAddress(location) {
currgeocoder.geocode({
'location': location
}, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
console.log(results[0]);
$("#address").html(results[0].formatted_address);
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
});
Try this-
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&signed_in=true"></script>
<script type="text/javascript">
$(document).ready(function(){
function getGeoLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
document.getElementById("address").value = "Geolocation is not supported by this browser.";
}
}
function showPosition(position) {
var lat = position.coords.latitude;
var lang = position.coords.longitude;
var url = "http://maps.googleapis.com/maps/api/geocode/json?latlng=" + lat + "," + lang + "&sensor=true";
$.getJSON(url, function (data) {
var address = data.results[0].formatted_address;
document.getElementById("address").value = address;
});
}
});
</script>
The url http://maps.googleapis.com/maps/api/geocode/json?latlng=22.3545947,91.8128751&sensor=true returns address information in JSON format. You want the "formatted_address" of 0 index inside the "result" index of the JSON.
See the JSON file for more information.
In order to start using Google Maps API, you need to include the Google Maps JS file into your script.
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY"></script>
You need to replace YOUR_API_KEY with your own key. You need to generate one for your application.
Get API Key
There is another issue in your code at this line.
$("#address").html(results[0].formatted_address);
The element with id="address" is an input field, so the .html() function is not available on it. You need to use the .val() function. So you can replace that line with the one below.
$("#address").val(results[0].formatted_address);
This should get your code working.
The reason your textfield is not being populated with the address is because of this line in your code:
In "getCurrentAddress" function:
$("#address").html(results[0].formatted_address);
The problem, in this line is that you want to set an input "textfield". In this case you cannot do .html()
You can fix this by changing it to:
$("#address").val(results[0].formatted_address);
Take a look at the following fiddle:
https://jsfiddle.net/ezr6z7so/
I have some code that saves the users input into local storage and then prints the value into the selected ID.
function saveData() {
var input = document.getElementById("saveServer");
localStorage.setItem("server", input.value);
console.log(localStorage.getItem("server"));
document.getElementById("yourname").innerHTML ="Okay " + (localStorage.getItem("server")) + " Let's get started! Push the button on the right to begin the story!" ;
}
How do I make it so if the input field is empty a statement is produced informing the user to input their name.
I've had a look at if and else statements but anything I try doesn't seem to work.
Edit:
Figured it out!
if (saveServer.value == "") {
document.getElementById("yourname").innerHTML = "Please input your name";
}
else {
document.getElementById("yourname").innerHTML ="Okay " + (localStorage.getItem("server")) + " Let's get started! Push the button on the right to begin the story!" ;
}
Add a condition to check if input not empty.
function saveData() {
var input = document.getElementById("saveServer").value;
if(input ==="") alert("Enter saveServer");
else{
localStorage.setItem("server", input.value);
console.log(localStorage.getItem("server"));
document.getElementById("yourname").innerHTML ="Okay " + (localStorage.getItem("server")) + " Let's get started! Push the button on the right to begin the story!" ;
}
}
Like this:
function saveData() {
var input = document.getElementById("saveServer");
localStorage.setItem("server", input.value);
var serverValue = localStorage.getItem("server");
if (!serverValue) {
document.getElementById("error").innerHTML = "Oh dear! Nothing was found";
}
document.getElementById("yourname").innerHTML = "Okay " + (localStorage.getItem("server")) + " Let's get started! Push the button on the right to begin the story!";
}
Fiddle: http://jsfiddle.net/KyleMuir/LhyXr/
Please check out the code below. I want to get the value entered in the prompt box into function dis(). How can I do that?
<!DOCTYPE html>
<html>
<head>
<script>
function display()
{
var z=prompt("enter your name...");
if(z!=null)
{
document.getElementById("demo").innerHTML="thankyou"+z+"..";
document.getElementById("case").style.display='block';
}
else
document.getElementById("demo").innerHTML="thankyou";
}
function dis()
{
var a=document.getElementById("aaa").value;
alert("your mark is"+a);
}
</script>
</head>
<body>
<p id="demo">click on the button.....</p>
<button type="button" onclick="display()">submit</button>
<div id="case" style="display:none">
<input type="text" id="aaa" name="myText" onDblClick="dis()">enter your mark
</div>
</body>
</html>
If you want to directly pass value to dis() function then change your script to
function display() {
var z = prompt("enter your name...");
if (z != null) {
document.getElementById("demo").innerHTML = "thankyou " + z + "..";
document.getElementById("case").style.display = 'block';
dis(z);
}
else
document.getElementById("demo").innerHTML = "thankyou";
}
function dis(arg) {
alert("your mark is" + arg);
}
If you want the value to be accessible from independent functions you'll need to store it in a global variable:
<script>
var userName = null;
function display() {
userName = prompt("enter your name...");
if (userName != null) {
document.getElementById("demo").innerHTML="thankyou "+userName +"..";
document.getElementById("case").style.display='block';
} else
document.getElementById("demo").innerHTML="thankyou";
}
function dis() {
var a=document.getElementById("aaa").value;
alert(userName + ", your mark is"+a);
}
</script>
Note that if the functions are completely independent they'll all need to test whether the variable has a value yet. In your case the dis() function is only called from a control that is made visible after a value has been set, but note that the user might click the button again and then cancel - in which case the name will be set back to null but the case element will still be visible.