不可编辑的jQuery自动完成

时间:2015-11-06 04:52:22

标签: javascript jquery

我们正在尝试实现不可编辑的jQuery自动完成功能。例如,当用户从自动完成中选择值时,他们无法修改它。但是当他们按退格键时,旧值会被删除,并且他们可以再次从自动完成中选择新值 我们知道有很多插件,但我们不想使用任何插件。

这是我们正常自动完成的jsfiddle。

Jsfiddle

以下是具有此功能的插件。

plugin

我们的守则

$(document).ready(function () {
    var aTags = ["ask", "always", "all", "alright", "one", "foo",
        "blackberry", "tweet", "force9", "westerners", "sport"
    ];

    $("#tags").autocomplete({
        source: aTags
    });
});

HTML:

<input type='text' title='Tags' id='tags' />

3 个答案:

答案 0 :(得分:2)

更新:尝试捕获退格,然后将字段设置为空白。如果要在选择中设置字段$ ./buf < over Enter a password of length between 1 and 15 characters : warning: this program uses gets(), which is unsafe. Enter your password : Wrong Password Root privileges given to the user ,则可以选择readonly

&#13;
&#13;
autocomplete
&#13;
&#13;
&#13;

FIDDLE WITH YOUR ANGULAR SCRIPT

答案 1 :(得分:0)

以下是此解决方案。这符合我的要求。可能会帮助一个人。

Working Solution

HTML: -

<input id="field" type="text" placeholder="test" value="" size="50" />
<div id="output">
</div>

JS:

var readOnlyLength = $('#field').val().length;
var tmpFlag=true;
var aTags = ["ask","always", "all", "alright", "one", "foo", "blackberry", "tweet","force9", "westerners", "sport"];


 $( "#field" ).autocomplete({
    source: aTags,
   select: function( event, ui ) {
   tmpFlag=false;
   }
});
$('#output').text(readOnlyLength);

$('#field').on('keypress, keydown', function(event) {
var $field = $(this);

 if(event.which==8){
    $('#field').val('');
                   tmpFlag=true;

}

console.log(tmpFlag);
if(tmpFlag==false)
if ((event.which != 37 && (event.which != 39))
    && ((this.selectionStart < readOnlyLength)|| (this.selectionStart <= readOnlyLength) ||(this.selectionStart > readOnlyLength) 
    || ((this.selectionStart == readOnlyLength) && (event.which == 8)))) {
     event.preventDefault();
}


});                      

答案 2 :(得分:-1)

尝试这样的事情:

app.controller('formController', function ($scope) {
    // your code
}

DEMO

这里在var aTags = ["ask","always", "all", "alright", "one", "foo", "blackberry", "tweet","force9", "westerners", "sport"]; $( "#tags" ).autocomplete({ source: aTags }); $( "#tags" ).blur(function(){ var tag = $(this).val(); if(jQuery.inArray(tag,aTags) == -1){ // the element is not in the array $( "#tags" ).val(''); } }); 我检查输入值是否在数组中,如果不是,我清除输入字段。