且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

文本字段自动完成-仅允许在自动完成选项中提交

更新时间:1970-01-01 07:57:42

以下解决方案,它利用 jQuery UI Autocomplete 就足够了-当然,根据您的特定要求,可能需要进一步调整.

The following solution, which utilises jQuery UI Autocomplete, should suffice - of course it might need some further tweaking depending on your specific requirements.

标记:

<input id="autocomplete"/>
<br />
<input id="submit" type="submit" disabled="disabled"/>

脚本:

var source = ['One', 'Two', 'Three', 'Four'];

$("input#autocomplete").autocomplete({
    source: source,
    select: function(event, ui) {
        $("#submit").removeAttr("disabled");
    }
}).keyup(function() {
    var $parentContext = $(this);
    var matches = $.grep(source, function(n, i) {
        return $parentContext.val().toLowerCase() == n.toLowerCase();
    });
    $("#submit").attr("disabled", !matches.length);
});

演示: http://jsfiddle.net/karim79/Ezbns/

进一步阅读:

  • http://jqueryui.com/demos/autocomplete/
  • http://api.jquery.com/jQuery.grep/