0

我有一些代码,当单击搜索框时,会在位置框中对位置进行地理编码(除非自动建议已完成),并且应该提交表单。

问题是,单击搜索按钮并且地理编码成功后,表单没有提交。谁能告诉我哪里出错了?

这是 jsfiddle 的链接:http: //jsfiddle.net/sR4GR/35/

这是完整的代码:

$(function () { 

    var input = $("#loc"),
        lat = $("#lat"),
        lng = $("#lng"),
        lastQuery = null,
        autocomplete;

    function processLocation(query) {
        var query = $.trim(input.val()),
            geocoder;

        if (!query || query == lastQuery) {
            console.log("Empty or same variable");
            return;
        }

        lastQuery = query;

        geocoder = new google.maps.Geocoder();
        geocoder.geocode({
            address: query
        }, function (results, status) {
            if (status === google.maps.GeocoderStatus.OK) {
                lat.val(results[0].geometry.location.lat());
                lng.val(results[0].geometry.location.lng());
            } else {
                alert("We couldn't find this location. Please try an alternative");
            }
        });
    }

    autocomplete = new google.maps.places.Autocomplete(input[0], {
        types: ["geocode"],
        componentRestrictions: {
            country: "uk"
        }
    });

    google.maps.event.addListener(autocomplete, 'place_changed', processLocation);

    $('#searchform').on('submit', function (event) {
        processLocation();
        event.preventDefault();
    });
});
4

2 回答 2

1

我不知道processLocation(query)期望什么query,但想法是这样的:
1.更改函数签名

function processLocation(query, doSubmit) { // <--- new parameter
    var query = $.trim(input.val()),
        geocoder;

    if (!query || query == lastQuery) {
        console.log("Empty or same variable");
        return;
    }

    lastQuery = query;

    geocoder = new google.maps.Geocoder();
    geocoder.geocode({
        address: query
    }, function (results, status) {
        if (status === google.maps.GeocoderStatus.OK) {
            lat.val(results[0].geometry.location.lat());
            lng.val(results[0].geometry.location.lng());
            if (doSubmit){
                 $('#searchform').submit(); //<-- new param usage
            }
        } else {
            alert("We couldn't find this location. Please try an alternative");
        }
    });
}

2.删除这个电话

$('#searchform').on('submit', function (event) {
    alert('Submitted')
    event.preventDefault(); 
});

3.添加这个调用

$('#search').click(function(){
     processLocation(new Date(), true); //<-- don't know what's the first param
});

试图在你的 jsfiddle 中玩耍,但没有成功,因为我不断地将Empty or same variable消息输入控制台。我想你更了解你的逻辑,你会弄清楚

于 2013-05-16T09:36:23.560 回答
0

我只会禁用提交按钮,直到值有效?

<input type="submit" value="Search" id="search" disabled="disabled">

search.removeAttr('disabled')

http://jsfiddle.net/sR4GR/38/

?

于 2013-05-16T09:33:34.820 回答