每次用户键入时调用函数

Calling a function everytime user types

本文关键字:调用 函数 用户      更新时间:2023-09-26

我有以下函数,每次我都想被调用,用户在typeahead输入字段中键入一些内容。

function getAllActiveUsers() {
    var userList = $('#usersTable').jqGrid('getGridParam').userData;
    var userNames = {};
    if(userList) {
        // Return the list  of all active users
        $(userList).each(function() {
            if(this.userStatus != 1) {
                // If the user is verified
                // Could be active/inactive
                userNames.user = this.username;
            }
        });
    }
    return JSON.stringify(userNames);
}

HTML:

 <div id="the-basics">
   <input class="typeahead" type="text" data-provide="typeahead" placeholder="User List">
</div>

我一直在浏览示例,但不明白如何实现此功能。

编辑

为什么当我初始化为时它不起作用

$('.typeahead').typeahead({
    source : getAllActiveUsers
});

试试这个

$(document).ready(function(){
   $('.typeahead').keyup(function(){
       getAllActiveUsers();
   });
});

您可以使用.keyup jquery函数

$( ".typeahead" ).keyup(function() {
  getAllActiveUsers();
});

根据您提供的引用,您可以在id #the-basics:中指定类.typeahead

$(document).ready(function(){
  $('#the-basics .typeahead').typeahead({
    //code here;
  }
}

由于在文档准备好之前无法安全地操作页面,因此应该使用$(document).ready
此外,请尝试使用浏览器控制台并检查是否可以访问$('#the-basics .typeahead')

您可以使用Jquery Keyup,它在释放键时被触发。

$( ".typeahead" ).on('keyup',function() {
  getAllActiveUsers();
});

如果你的文本框是动态的,那么你应该尝试

$(document).on("keyup", ".typeahead" , function() {
  getAllActiveUsers();
});

试试这个,让我们知道它是否有效。

这应该是可能的

var getAllActiveUsers = function(q, cb, cb2) {
  // cb for sync, cb2 for async
  var userList = $('#usersTable').jqGrid('getGridParam').userData;
  var filterted = /* whatever you want to do with q */;
  cb(filtered);
};
$('.typeahead').typeahead({
    /* Options */
},
{
    source : getAllActiveUsers
});