2011-07-18 25 views
1

我在頁面上創建了一個動態下拉列表。當從下拉列表中選擇一個選項時,我如何才能讓它觸發jquery函數?如何在OnSelectedChange上關閉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 
      } 

回答

2

Store中的下拉列表中受保護的領域在代碼隱藏,然後:

$('<%=_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); 
0

你找jQuery's change事件。

它會是這個樣子:

$('#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; 
} 

+0

但我有多個下拉列表在我的網頁上有多個ID。我會怎麼做? –

+1

向他們添加一個類,並將其定位到所有目標。因此而不是'$('#DropdownlistID')。change'就是'$('。DropDownListItem'),change'或者任何想要分配給下拉菜單的類。您也可以將'select'標籤作爲目標,但這會監聽頁面上所有下拉菜單的事件 – locrizak

相關問題