如何使用jquery .val()从自动完成输入中获取值?

时间:2016-06-08 16:36:22

标签: javascript jquery autocomplete

我无法使用jquery .val()获得自动完成输入,因为.val()只返回由我自己输入的输入值,而不是自动完成添加的输入值。

如果在其他字段上进行更改,则jquery .val()仅返回完整值。

我使用谷歌地图自动填充地址,而不是我将该地址传递给谷歌地图api以获得两个地址之间的距离。问题是这个“start = $('#id_rent_delivery_address')。val()”只获取手动键入但未自动填充的地址部分。

也许你对我如何解决它有任何想法?

我的代码:

<script>

    $(document).ready(function() {
        initAutocomplete();
    });

    var autocomplete, autocomplete2;

    function initAutocomplete() {
        // Create the autocomplete object, restricting the search to geographical
        // location types.
        autocomplete = new google.maps.places.Autocomplete(
                /** @type {!HTMLInputElement} */(document.getElementById('id_rent_withdraw_address')),
                {types: ['geocode']});


        autocomplete2 = new google.maps.places.Autocomplete(
                /** @type {!HTMLInputElement} */(document.getElementById('id_rent_delivery_address')),
                {types: ['geocode']});

        // When the user selects an address from the dropdown, populate the address
        // fields in the form.

    }

</script>





<script type="text/javascript">

$(document).on('change', '#rent-confirm-form', function() {

    var start = $('#id_rent_delivery_address').val();
    var end = $('#id_rent_withdraw_address').val();

    GetRoute(start, end);

});   

    function GetRoute(start, end) {
        //*********DISTANCE AND DURATION**********************//
        var service = new google.maps.DistanceMatrixService();
        service.getDistanceMatrix({
            origins: [start],
            destinations: [end],
            travelMode: google.maps.TravelMode.DRIVING,
            unitSystem: google.maps.UnitSystem.METRIC,
            avoidHighways: false,
            avoidTolls: false
        }, function (response, status) {
            if (status == google.maps.DistanceMatrixStatus.OK && response.rows[0].elements[0].status != "ZERO_RESULTS") {
                var distance = response.rows[0].elements[0].distance.text;
                var duration = response.rows[0].elements[0].duration.text;

                console.log(distance);
                console.log(duration);
                console.log(start);
                console.log(end);

            } else {
                console.log("Unable to find the distance via road.");
            }
        });
    }

</script>

1 个答案:

答案 0 :(得分:0)

由我自己解决。只需使用jquery触发器方法模拟表单更改。

$( "#anyInput" ).trigger("change");