0

I have ddl(drop down list) which populates from database after change event of another ddl but I want to change the value of this ddl after it populated from database.

Example:

// This work very well
$("#ddlGroups").on('change',function(){
    // Load data from database and populate ddlUsers
    // response is loaded from database with $.ajax
    // Query Example: SELECT User_ID, Username FROM tblUsers WHERE Group_ID = [Group_ID] (Just for undrestanding the question)

    var Records = response.d;
    $("#ddlUsers").empty();
    $.each(Records, function(){
    var _Key = this.User_ID;
        _Value = this.Username;
        $("#ddlUsers").append($("<option />").val(_Key).text(_Value));
    });
});

// When button clicked then trigger ddlGroups change event and assign select option from ddlUsers
var _UserID = User_ID_From_Database; // Loaded from Database when button clicked
$("#ddlGroups").trigger('change'); // Users are loaded from database based on group ID
$("#ddlUsers").val(_UserID); // But this dosn't change

How do I check if ddlUsers is loaded or not, I tried while loop but it never stops.

4

1 回答 1

0

使用 jquery 有两种主要方法(实际上是相同的底层)将来自数据库的 ajax 响应连接到事件或 UI 结果。第一个是承诺,第二个是回调。这两个都有 100 万个示例,并且 jquery 文档非常健壮。

在您的情况下,您回调调用正确的函数而不是“触发”。下面只是显示的垃圾代码。

No:  $("#ddlGroups").tigger('change'); 

Yes:
//Your code 
$("#ddlGroups").on('change', updateDDL);

//I have just externalized this function to a scope/place where both the ajax and on change line of code can reference it.
function updateDDL(){

    var Records = response.d;
    $("#ddlUsers").empty();
    $.each(Records, function(){
    var _Key = this.User_ID;
        _Value = this.Username;
        $("#ddlUsers").append($("<option />").val(_Key).text(_Value));
    }
};

$.ajax(...., function (data) {
// Update ddl, the existing function you have.
// You should already have something like this.
updateDDL();  //Like this
});

顺便说一句:您可以将数据直接传递到 updateDDL 中,在 updateDDL 中使用 $(this) 来改进它等,但这不是您的问题/问题的关键。您似乎对 jquery 和它使用的一些 Javascript 功能不熟悉。花一点时间来了解它们,你会得到很好的回报。我将首先阅读有关 ajax/jquery 的示例,然后观察如何更新 DOM。

于 2013-10-31T18:23:41.807 回答