2

我正在使用 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());
                        }
                    });

如果我按标签,它工作正常。
如果未选择自动完成结果中的值,谁能告诉我如何限制提交表单?

4

1 回答 1

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;
});
于 2012-12-29T13:26:25.400 回答