如何在OnSelectedChange上启动jquery函数?

本文关键字:jquery 函数 启动 OnSelectedChange | 更新日期: 2023-09-27 18:02:45

我正在我的页面上创建一个动态下拉列表。当从下拉菜单中选择一个选项时,我如何让它触发jquery函数?

Jquery:

            <script type="text/javascript">
                $(document).ready(function () {
                   function insertIntoReporting(_storeID, _personID) {
                      $.ajax({
                        type: "POST",
                        url: "Default.aspx/InsertIntoReporting",
                        data: "{'storeID': _storeID, 'personID': _personID}",
                        contentType: "application/json; charset=utf-8",
                        dataType: "json",
                        async: true,
                        cache: false,
                        success: function (msg) {
                        $('').text(msg.d);
                         }
                       });
                      return false;
                   }
                });

            </script>

c#背后的代码

            DropDownList ddl = new DropDownList();
            ddl.ID = "DropdownlistID";
            ddl.Items.Add("----------");
            ddl.DataTextField = "StoreName";
            ddl.DataValueField = "StoreID";
            ddl.DataSource = ds;
            ddl.DataBind();
            e.Item.Cells[4].Controls.Add(ddl);

            [WebMethod]
            public static string InsertIntoReporting(int _storeID, string _personID)
            {
               // database calls go here
            }

如何在OnSelectedChange上启动jquery函数?

将下拉列表存储在代码隐藏的受保护字段中,然后:

$('<%=_ddl.ClientId%>').change(insertIntoReporting);

另一个选择是使您的insertIntoReporting函数更全局可访问,然后做这样的事情:

e.Item.Cells[4].Controls.Add(new LiteralControl(
    string.Format(
        @"<script>$(function() {   
            $('{0}').change(insertIntoReporting);
        });</script>",
        ddl.ClientId)));

还有另一种选择(我个人更喜欢)是添加一些类到所有的下拉列表,你想要有这种行为,并使你的javascript块包括一行,选择所有那些他们的类:

$('.report-insert-dropdown').change(insertIntoReporting);

查看jQuery的更改事件

它看起来像这样:

$('#DropdownlistID').change(insertIntoReporting);
function insertIntoReporting(_storeID, _personID) {
    // $(this) refers to the element that fired the event
    //In this case $(this).val() should be the equivilant as _storeId
    //im not sure where _personId is coming from so I will assume its in an input with id of personId
    var _storeId = $(this).val();
    var _personID = $('#personId').val();
    $.ajax({
        type: "POST",
        url: "Default.aspx/InsertIntoReporting",
        data: "{'storeID': _storeID, 'personID': _personID}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        async: true,
        cache: false,
        success: function (msg) {
            $('').text(msg.d);
            }
    });
    return false;
}