不可编辑的jQuery自动完成

Non editable jQuery auto-complete

本文关键字:jQuery 编辑      更新时间:2023-09-26

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

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

Jsfidle

这是具有此功能的插件。

插件

我们的代码

$(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' />

更新:尝试使用退格,然后将字段设置为空白。如果要在选择时设置字段readonly,可以在autocomplete的选择中进行。

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
 <script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script>
$(document).ready(function () {
var aTags = ["ask", "always", "all", "alright", "one", "foo",
    "blackberry", "tweet", "force9", "westerners", "sport"
];
$("#tags").autocomplete({
    source: aTags,
    select: function () {
    	$('#tags').prop("readonly",true);
      }
});
$('#tags').bind('keydown', function (event) {
    if (event.keyCode === 8) {
        event.preventDefault();
        $('#tags').prop("value","");
        $('#tags').prop("readonly",false);
    }
});
});
</script>
<style>
#tags:focus {
 border:1px solid #0000ff;
}
</style>
<input type='text' title='Tags' id='tags' />

FIDDLE与您的角度脚本

以下是解决方案。这符合我的要求。也许这会对某个人有所帮助。

工作溶液

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

});                      

试试这样的东西:

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

演示

blur function中,我检查输入值是否在数组中,如果不是,我清除输入字段。