views:

366

answers:

3

I have a multi-select <asp:listbox> and a button. I want to disable the button unless >= 1 item in the listbox is selected. How can I do this client-side? I can't find some sort of OnSelect callback, only OnSelectedIndexChanged which from googling seems complicated to use for this behavior, possibly impossible.

+1  A: 

OnClick or OnChange for a selectbox is the same thing as a "OnSelect".

Havenard
I don't think those attributes exist on <asp:ListBox> http://msdn.microsoft.com/en-us/library/z4d7ktzs.aspx
Dustin Getz
Well, they do exist in HTML which is what the user will be seeing after all.
Havenard
+2  A: 

Use OnChange event, and count the selected items :

<script>function enableButton(opt) {
      var selected = new Array();
      var count = 0;
      for (var intLoop=0; intLoop < opt.length; intLoop++) {
         if (opt[intLoop].selected) {
            count++;
         }
      }
      if (count >= 1)
      {
       // disable button
      }
   }
</script>

<select id="list" style="font-size: 11px;"   
    onChange="enableButton(this.options);" MULTIPLE SIZE="5">
    <option value="0">Select...</option>
    <option value="1">1</option>
    <option value="2">2</option>
</select>

EDIT : ASP:ListBox rendered to HTML as select as the code above. So all you need to do is to add the script at the onchange attribute :

myListBox.Attributes.Add("onchange", "enableButton(this.options);");
Canavar
I'm using the declarative asp:listbox syntax. Do additional attributes that aren't recognized by ASP fall through to the rendered html?
Dustin Getz
Almost all the client events are messing the server side events :) So they added some properties to some components like OnClientChange that refers to OnChange.
Canavar
+2  A: 

This wouldn't be so hard to do using jQuery. Something along the lines of -

$("select#myListBox").change(function() {
   if ($("select#myListBox option:selected").length >= 1)
      $("input#myButton").attr("disabled", "true");
}

All hail the mighty jQuery.

Jagd