简体   繁体   English

我想在输入字段输入后运行函数

[英]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. 我有一个小表格,当前使用按钮从Google Maps API获取纬度和经度,并将结果放入输入字段。 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. 这是我在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/ 更新小提琴: https : //jsfiddle.net/z6874xou/10/

Check this code JS Fiddle . 检查此代码JS Fiddle I have added onchange event for city input box 我为城市输入框添加了onchange事件

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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