views:

3829

answers:

2

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.

+6  A: 

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>
Jose Basilio
I changed "onclick" to "onchange" and it still doesn't work.
Mike C.
It shouldn't be attached to the items, but to the list itself.
Jose Basilio
Is there a way I can attach it to the items like on a RadioButtonList? That's what I'm trying to get at.
Mike C.
Yes, that was the work around I had been doing, but I thought I would check to see if I could handle it the same was I was with a RadioButtonList. That's interesting that they are different. Thank you.
Mike C.
The reason is because in a RadioButtonList, each item becomes an independent <input type="radio"> element and as such can handle its own events. The dropdownlist on the other handle is just one single html element with options underneath.
Jose Basilio
You don't need the "javascript:" pseudo-protocol. It is required only on "href" attribute of an anchor and strongly discouraged there too.
Chetan Sastry
@Chetan - Thank you for pointing that out. Good observation.
Jose Basilio
@Jose, Thanks for the explanation!
Mike C.
+1  A: 

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 ;)

Fox
@Fox - those are the correct server side events. However, He is looking for the client side events.
Jose Basilio
My bad, sorry. OnClick is the one on client side as you said...
Fox