Jquery - 表单未提交

时间:2013-05-16 09:16:15

标签: javascript jquery performance

我有一些代码,当点击搜索框时,会对位置框中的位置进行地理编码(除非已经由autosuggest完成),并且应该提交表单。

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

这是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();
    });
});

2 个答案:

答案 0 :(得分: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消息到控制台。我认为你更了解你的逻辑并且你会弄清楚

答案 1 :(得分:0)

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

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

search.removeAttr('disabled')

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