【问题标题】:how to get id of selected list data in the jquery mobile autocomplete如何在jquery移动自动完成中获取所选列表数据的ID
【发布时间】:2013-09-06 05:06:00
【问题描述】:

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

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

但我不知道如何在 jQuery mobile 中执行此操作。

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

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

    });
}); });

如果能给出同样的小例子就好了。

感谢任何建议。提前致谢。

【问题讨论】:

    标签: javascript android jquery-mobile autocomplete cordova-2.0.0


    【解决方案1】:

    我不确定我是否理解了这个问题,但我认为除了将用户名作为显示文本之外,您正在寻找的是将用户 ID 存储在 &lt;li&gt; 元素中。

    这样的事情可能会为您完成这项工作:

    // 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.push(...) 而不是使用 usrids[i] = ...;当给定数组中不存在元素 i 时。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-02-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多