避免并禁用输入字段的自动填充

时间:2018-06-26 10:46:44

标签: jquery html css

当我在表单中使用多个输入时,自动完成功能不起作用,但如果输入一项,则可以正常使用。 我正在使用此表单使用Google api获取地址,而每次要添加新地址时都会出现问题,我会看到先前的输入

enter image description here

<form autocomplete="off" id="form_address" >
    <input type="text" id="postal_code" onFocus="geolocate()">
    <input type="text" id="city">
    <textarea placeholder="Delivery Instructions"></textarea>
</form>  


<script>
    var placeSearch, postal_code;
    var componentForm = {
        locality: 'long_name',
        administrative_area_level_1: 'short_name',
        country: 'long_name',
    };

    function initAutocomplete() {
        postal_code = new google.maps.places.Autocomplete((document.getElementById('postal_code')),
        {types: ['geocode']});
        postal_code.addListener('place_changed', fillInAddress);
    }

    function fillInAddress() {
        var place = postal_code.getPlace();

        for (var component in componentForm) {
            document.getElementById(component).value = '';
            document.getElementById(component).disabled = false;
        }

        for (var i = 0; i < place.address_components.length; i++) {
            var addressType = place.address_components[i].types[0];
            if (componentForm[addressType]) {
                var val = place.address_components[i][componentForm[addressType]];
                document.getElementById(addressType).value = val;
            }
        }
    }

    function geolocate() {
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(function(position) {
            var geolocation = {
                lat: position.coords.latitude,
                lng: position.coords.longitude
            };
            var circle = new google.maps.Circle({
                center: geolocation,
                radius: position.coords.accuracy
            });
            postal_code.setBounds(circle.getBounds());
            });
        }
    }
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDDSzHOBeXL_Goaj4tecH3l0YTJ7anf2rc&libraries=places&callback=initAutocomplete" async defer></script>

1 个答案:

答案 0 :(得分:0)

您应该在表单和输入元素上也不要使用自动填充功能

<form autocomplete="off" id="form_address"> <input type="text" autocomplete="off" id="postal_code" onFocus="geolocate()"> <input type="text" id="city"> <textarea placeholder="Delivery Instructions"></textarea> </form>