2012-12-19 94 views
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()); 
         } 
        }); 

它工作正常,如果我按tab。
任何人都可以告诉我如何限制提交表单,如果从自动完成结果的值未选中?

回答

0

你的钥匙不要在那里工作,因为它是一个默认的浏览器行为提交表单,你需要提取表单提交ins按下输入。

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; 
});