如何动态获取期权价值指数?

时间:2013-08-18 09:34:11

标签: jquery jquery-mobile

我有一个选择列表。我想在选择选项时找到索引。从数据库中获取的选项值,但索引未刷新。这是我的代码

function loadListPenyakit(){
        $.ajax({
            type: 'get',
            url: 'http://10.0.2.2.com/compfest/ajax/belajar/list_p.php',
            success: function(response){
                var file = '';
                $.each(response, function(index, item){
                    file += '<option value='+$("select[name='select-choice-b'] option:selected").index()+'>' + item.penyakit + '</option>';
                });
                $('#select-choice-b').html(file).selectmenu().selectmenu('refresh', true);
            },
            error: function(e){
                alert('Communication Server Error ');
            }
        });
    }

当我从数据库获取数据时,Index值为0.这意味着没有刷新。 请帮帮我!

1 个答案:

答案 0 :(得分:1)

你不能这样使用索引。您必须在change事件中编入索引并将其发送到ajax调用。根据您现在所拥有的,您将选项值设置为不存在的值。 Here's a demo for what you're looking for.

这是JS:

$(document).on("pageinit", "#first", function () {
    //  $.ajax({
    //        type: 'get',
    //      url: 'http://10.0.2.2.com/compfest/ajax/belajar/list_p.php',
    //   success: function(response){

    //assume i got this from an ajax call
    var response = [{
        "penyakit": "tempor"
    }, {
        "penyakit": "consequat"
    }, {
        "penyakit": "non"
    }, {
        "penyakit": "esse"
    }, {
        "penyakit": "magna"
    }, {
        "penyakit": "laboris"
    }, {
        "penyakit": "cupidatat"
    }, {
        "penyakit": "eiusmod"
    }, {
        "penyakit": "nostrud"
    }, {
        "penyakit": "quis"
    }, {
        "penyakit": "ullamco"
    }, {
        "penyakit": "in"
    }, {
        "penyakit": "esse"
    }, {
        "penyakit": "ullamco"
    }, {
        "penyakit": "non"
    }]

    var file = '';
    $.each(response, function (index, item) {
        //dont use index now. it can be collected only during runtime ie., only when the dropdown changes
        file += '<option>' + item.penyakit + '</option>';
    });
    $('#select-choice-b').html(file).selectmenu().selectmenu('refresh', true);

    //  },
    //  error: function (e) {
    //    alert('Communication Server Error ');
    //  }
    //});


    //index must be taken in the change event
    $(this).on("change", "select", function () {
        var index = $(":selected", this).index();
        //use index variable to make ajax call now. 
        alert(index);
    });

});