如何在jquerymobile自动完成中获取所选列表数据的id

how to get id of selected list data in the jquery mobile autocomplete

本文关键字:获取 列表 数据 id jquerymobile      更新时间:2023-09-26

我正在创建一个应用程序,在其中我使用了jQuery mobile自动完成列表视图数据是从数据库中动态创建的,自动完成的列表视图代码返回到js文件中。我可以从列表视图中选择数据,并将其显示在自动完成的输入字段中,然后禁用搜索列表。

我想知道的是,当用户选择列表数据时,它会显示名称,但当它单击保存按钮时,它应该保存该名称的id,而不是jQuery ui中的名称。自动完成它很容易,因为在那里我们可以使用带标签和值的数组。

但我不知道如何在jQuery手机上做到这一点。

在这里创建自动完成的代码:

var db = window.openDatabase("Database", "1.0","BPS CRM", 200000);
$( document ).on( "pageinit", "#myPage", function() {
var usrname = new Array();
$( "#autocomplete" ).on( "listviewbeforefilter", function ( e, data ) {
    var $ul = $( this ),
        $input = $( data.input ),
        value = $input.val(),
        html = "";
    $ul.html( "" );
    db.transaction(function(tx){
        tx.executeSql('select * from users',[],function(tx,results){
            var dataset = results.rows;
            if(dataset.length > 0){
            for(var i = 0; i < dataset.length; i++){
                    usrname[i] = dataset.item(i).user_name;
                }
            }
        });
    });
    if ( value && value.length > 1 ) {
                    for(var j = 0; j < usrname.length; j++){
                    html += "<li>"+usrname[j]+"</li>";
                }
         $ul.html( html );
         $ul.listview( "refresh" );
         $ul.trigger( "updatelayout");
         $.mobile.activePage.find('input[placeholder="Find a city..."]').attr('id','namesearch');
    }
    $("ul > li").click(function(){
        var textval = $(this).text();
        $('#namesearch').val(textval);
        $.mobile.activePage.find("[data-role=listview]").children().addClass('ui-screen-hidden');
    });
}); });

如果能举一个同样的小例子,那就太好了。

欢迎提出任何建议。提前谢谢。

我不确定我是否完全理解这个问题,但我认为您想要的是将用户ID存储在<li>元素中,此外还要将用户名作为显示文本。

像这样的东西可能对你有用:

// declare a collection of Ids where you declare usrname
var usrids = new Array();
// in your execute sql callback, add this line:
usrids.push(dataset.item(i).user_id);  // see note below
// in your for loop where you insert li's, modify the line like this :
html +="<li data-userid='" + usrids[j] + "'>"+usrname[j]+"</li>";
// then in your ul>li click event, you can reference your ids like this :
var userId = $(this).data('userid');

此外,作为一般注意事项,我认为最好使用usrids.push(…)和usrname.prush(……),而不是使用usrids[I]=。。。;当元素i还不存在于给定的数组中时。