自动完成力选择

时间:2012-12-19 09:50:15

标签: jquery javascript-events

我正在使用JQuery自动完成功能。问题是当我在文本框中输入任何无用的东西并单击提交按钮时。它不会在处理之前检查验证,因为在提交表单后会调用change方法。

var fromAutocomplete = this.$("#fromCity").autocomplete({
                        source : urlRepository.airportAutoSuggest,
                        minLength : 3,
                        select: function(event, ui) {
                            searchFormView.$("#fromCity").val(ui.item.label);
                            searchFormView.$("#fromCityCode").val(ui.item.value);
                            searchFormView.$('#fromCityCountry').val(ui.item.country);
                            isValid = true;
                            return false;
                        },
                        selectFirst: true,
                        change: function (event, ui) {
                            if (!ui.item) {
                                $(this).val('');
                            }
                        }
                    }).live('keydown', function (e) {
                        var keyCode = e.keyCode || e.which;
                        //if TAB or RETURN is pressed and the text in the textbox does not match a suggestion, set the value of the textbox to the text of the first suggestion
                        if((keyCode === 9 || keyCode === 13) && ($(".ui-autocomplete li:textEquals('" + $(this).val() + "')").size() === 0)) {
                            $(this).val($(".ui-autocomplete li:visible:first").text());
                        }
                    });

如果按Tab键,它可以正常工作 如果未选择自动填充结果中的值,是否可以告诉我如何限制提交表单?

1 个答案:

答案 0 :(得分:0)

你的密钥不能在那里工作,因为它是提交表单的默认浏览器行为,你需要获取提交输入的表单提交。

var fromAutocomplete = this.$("#fromCity").autocomplete({
    source : urlRepository.airportAutoSuggest,
    minLength : 3,
    select: function(event, ui) {
        searchFormView.$("#fromCity").val(ui.item.label);
        searchFormView.$("#fromCityCode").val(ui.item.value);
        searchFormView.$('#fromCityCountry').val(ui.item.country);
        isValid = true;
        return false;
    },
    selectFirst: true,
    change: function (event, ui) {
        if (!ui.item) {
            $(this).val('');
        }
    }
}).live('keydown', function (e) {
    var keyCode = e.keyCode || e.which;
    //if TAB is pressed and the text in the textbox does not match a suggestion, set the value of the textbox to the text of the first suggestion
    if( keyCode === 13) && ($(".ui-autocomplete li:textEquals('" + $(this).val() + "')").size() === 0)) {
        $(this).val($(".ui-autocomplete li:visible:first").text());
    }
}).closest('form').submit(function() {
    //if RETURN is pressed and the text in the textbox does not match a suggestion, set the value of the textbox to the text of the first suggestion
    $(this).val($(".ui-autocomplete li:visible:first").text());

    return false;
});
相关问题