Search code examples
javascriptjquerycomboboxjquery-eventsajaxcontroltoolkit

How do I bind a Javascript event handler to the Ajax Control Toolkit combobox when textbox changed


I need a combobox for an ASP.NET project, so I decided to use the Ajax Control Toolkit combobox (http://www.asp.net/AJAX/AjaxControlToolkit/Samples/ComboBox/ComboBox.aspx).

I don't want to use the postback as I don't want the page reloaded, but I need to know when the text in the textbox is changed so I can call out to the server to persist the new list item.

I am curious how I bind an onchange or onblur event to the input box that this combobox uses.

This is my asp.net page:

<%@ Register assembly="AjaxControlToolkit" namespace="AjaxControlToolkit" tagprefix="cc1" %>

<cc1:ComboBox ID="PlantDropDown" runat="server" OnInit="PlantDropDown_Init" DropDownStyle="DropDown" 
             AutoCompleteMode="SuggestAppend" 
            ItemInsertLocation="OrdinalText" AutoPostBack="false">


                </cc1:ComboBox>

Update: I tried using the suggestion and I get this error:

$find("PlantDropDown") is null
[Break on this error]
$find('PlantDropDown').add_propertyChanged(function(sender, e) {\r\n

I am using jQuery for the Javascript side, btw, in case that helps.

Final Update:
I got it to work thanks to help from crescentfresh, and at the end I have this in my .aspx file:

<input type="hidden" id="PlantDropDownID" value="<%= PlantDropDown.ClientID %>" />

And this is in my javascript file, since I don't push javascript in my .aspx file:

elem = document.getElementById('PlantDropDownID');
$find(elem.value).add_propertyChanged(function(sender, e) {
    if (e.get_propertyName() == 'selectedIndex') {
        var newValue = sender.get_textBoxControl().value;
    }
})

Solution

  • I believe you are supposed to bind to the "propertyChanged" event and check for changes to the "selectedIndex" property:

    $find('PlantDropDown').add_propertyChanged(function(sender, e) {
        if (e.get_propertyName() == 'selectedIndex') {
            var newValue = sender.get_textBoxControl().value;
    
            // persist selected value here...
        }
    })
    

    with the usual caveat about .NET control ids in the client.

    The api is not easy, that's for sure. There is no .get_value() method for example, which would be nice instead of having to go through the embedded textbox control.

    Edit:

    > $find("PlantDropDown") is null

    Make sure you are using the correct id. See .NET control ids in the client. To get a reference you may have to do:

    $find('<%= PlantDropDown.ClientID %>')
    

    > I am using jQuery for the javascript side

    That holds no bearing.