简体   繁体   中英

I want to run a function after an input field has been entered

I have a small form that currently uses a button to get the latitude and longitude from Google Maps API and puts the results into an input field. The trigger is a event listener on the button. I want to get rid of the button and after the city has been added trigger the event. I am not sure how this is accomplished. Here is my code in JS fidler. enter link description here

function showResult(result) {
    document.getElementById('latitude').value = result.geometry.location.lat()   +' '+ result.geometry.location.lng();

}

function getLatitudeLongitude(callback, address) {
     // If adress is not supplied, use default value 'Ferrol, Galicia, Spain'
address = address || 'Ferrol, Galicia, Spain';
    // Initialize the Geocoder
    geocoder = new google.maps.Geocoder();
    if (geocoder) {
        geocoder.geocode({
            'address': address
        }, function (results, status) {
            if (status == google.maps.GeocoderStatus.OK) { 
                callback(results[0]);
            }
        });
    }
}

var button = document.getElementById('btn');

button.addEventListener("click", function () {
    var address = document.getElementById('street').value  +' '+ document.getElementById('city').value;
    getLatitudeLongitude(showResult, address)
});

Fire the event on change of city.

var city = document.getElementById('city');

city.addEventListener("change", function () {
    var address = document.getElementById('street').value  +' '+ document.getElementById('city').value;
    getLatitudeLongitude(showResult, address)
});

event on blur:

var city = document.getElementById('city');
city.addEventListener("blur", function () {
   var address = document.getElementById('street').value  +' '+ document.getElementById('city').value;
   getLatitudeLongitude(showResult, address)
});

update fiddle: https://jsfiddle.net/z6874xou/10/

Check this code JS Fiddle . I have added onchange event for city input box

 var city = document.getElementById('city');

 city.addEventListener("change", function () {
 var address = document.getElementById('street').value  +' '+ 
 document.getElementById('city').value;
 getLatitudeLongitude(showResult, address) 
});

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