How to handle cases when no item selection is performed but a string is present in the autocomplete field?

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-11 05:19:03

问题


I am using jQuery UI v1.9. I successfully implemented the jQuery UI Autocomplete widget but I have some trouble when I have to handle cases when a user doesn't select any item from the open menu but still continue to type letters in the related autocomplete field (that is, cases when the user continues to type letters even if the autocomplete menu is hidden because no item with the name as the entered one is present in that menu).

In such cases (when no item selection was performed but a string is present in the autocomplete field), I would like to alert the user that he / she is no selecting an existing object but that he / she is typing a custom one. How can I make that?


Note: Practically speaking, I am trying to force the user to select an existing item or, if that was not selected, to prompt he / she to create a new one.


回答1:


You can set a callback function for the change event of autocomplete plugin where you should be able to check if an item has been selected:

$( "#autocomplete" ).autocomplete({
     change: function(e,ui){
         if(ui.item === null)
           alert('No item has been selected')  
    }
});

UPDATE:

If you want to trigger change event before input loses focus, you could use following code, triggering it on keypress event:

$( "#autocomplete" ).autocomplete({
         change: function(e,ui){
             if(!ui || ui.item === null)
                 console.log('No item has been selected') 
        }
    }).on('keypress',function(){$(this).autocomplete('option','change').call()});


来源:https://stackoverflow.com/questions/13456321/how-to-handle-cases-when-no-item-selection-is-performed-but-a-string-is-present

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!