Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding "onclick" attribute to asp.net dropdownlist item

I can add an attribute to items in a RadioButtonList item like so:

PaymentMethodDropDownList.Items[0].Attributes.Add("onclick", "javascript:showNoMethods();");
PaymentMethodDropDownList.Items[1].Attributes.Add("onclick", "javascript:showCreditCardMethod();");
PaymentMethodDropDownList.Items[2].Attributes.Add("onclick", "javascript:showSendPaymentMethod();");

However, when I try to add the attributes to a DropDownList control it doesn't seem to work. I would expect it to be similar.

like image 832
Mike Cole Avatar asked May 04 '09 18:05

Mike Cole


2 Answers

This cannot be done in the same way as a radioButtonList, for a dropdownlist, the correct attribute event name is "onchange" instead of "onclick". The event should be attached to DropDownList Itself and not the items as follows:

PaymentMethodDropDownList.Attributes.Add("onchange",
                                            "showCreditCardMethod();");

Also, this is a little bit more complicated and requires a custom javascript function to perform a different action depending on the option selected. Here's an example:

PaymentMethodDropDownList.Attributes.Add("onchange",
                                             "handleDropDownEvents(this);");

Custom Javascript function: this assumes that values for the dropdown items are "CreditCard" and "SendPayment".

<script type="text/javascript">
    function handleDropDownEvents(e){
      if(e.value == "CreditCard"){
         showCreditCardMethod();
      }
      else if(e.value == "SendPayment"){
        showSendPaymentMethod();
      }
    }
</script>
like image 132
Jose Basilio Avatar answered Sep 17 '22 12:09

Jose Basilio


Actualy for a DropDownList in ASP .Net, the property you're looking for is OnSelectedIndexChanged or OnTextChanged . Both does quite the same job.

Hope this help ;)

like image 24
Marc-Andre R. Avatar answered Sep 16 '22 12:09

Marc-Andre R.