2

I've been at this for 12+ exhausting hours trying get it to work on my page. Below I will include my codebehind (list source & getter), my jQuery (in the header wrapped in the "ready" function), and my asp.net dropdownlist control, button, and input objects wrapped in a div. Here is the combobox I'm trying to implement. Nothing I have found yet has helped. It seems it's an issue with linking actions and values together. Namely, the button does not toggle the dropdownlist to expand.

To make it easier, I've made all caps comments in the codeboxes to point out specifically where I need help. There are only two things left to troubleshoot. Thanks maties :-)>

Now onto the codebehind --- (NOT THE MAIN ISSUE)

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    combobox.DataSource = car_list
    combobox.DataBind()
End Sub

Protected car_list As New ArrayList({
                                         "Audi",
                                         "Lexus",
                                         "BMW",
                                         "Ford",
                                         "Chevrolet",
                                         "Jeep",
                                         "Jaguar",
                                         "Toyota",
                                         "Nissan",
                                         "Honda",
                                         "Subaru",
                                         "Hyundai",
                                         "Tesla",
                                         "Mercedez",
                                         "Ferrari"
                                         })

//'This function returns the above list as either a String list, or wrapped in a tag
Function getList(ByVal listName As ArrayList, Optional ByVal tagWrapper As String = "", Optional ByVal tagId As String = "") As String
    Dim items As String = "No items in list."
    If Not tagWrapper = "" Then  //'Return as HTML Tagged Objects, a.k.a. Elements or DOM Objects or Nodes
        For Each item In listName
            If Not tagId = "" Then
                items = "<" + tagWrapper + " id=""" + tagId + """" + ">" //'Used if "id" parameter passed in
                items += item.ToString
                items += "</" + tagWrapper + ">" & vbCrLf
            Else
                items = "<" + tagWrapper + ">"
                items += item.ToString
                items += "</" + tagWrapper + ">" & vbCrLf
            End If
        Next
    Else //'Return as String Array, e.g. ["item1", "item2", "item3"]
        For Each item In listName
            Dim isFirstItem As Boolean = True
            If isFirstItem Then //'Treat the first item differently
                isFirstItem = Not isFirstItem
                items = item.ToString
            Else
                items += ", " + item.ToString
            End If
        Next
    End If

    Return items
End Function

The jQuery (again, in the header) - (HERE BE DRAGONS!)

$(document).ready(function () {
    $("#autocomplete").autocomplete({
        delay: 0,
        minLength: 0,
        autoFocus: true,
        //This "source:" function is pulled from the jQuery Combobox link above.
        source: function (request, response) {
            var matcher = new RegExp($.ui.autocomplete.escapeRegex(request.term), "i");
            response($("#combobox").children("option").map(function () {
                var text = $(this).text();
                if (this.value && (!request.term || matcher.test(text)))
                    return {
                        label: text.replace(
            new RegExp(
                "(?![^&;]+;)(?!<[^<>]*)(" +
                $.ui.autocomplete.escapeRegex(request.term) +
                ")(?![^<>]*>)(?![^&;]+;)", "gi"
//SOMETHING WRONG WITH THE REGEX REPLACE... THE "strong" TAGS ARE COMING THROUGH IN THE DROPDOWN :p
            ), "<strong>$1</strong>"),
                        value: text,
                        option: this
                    };
            }));
        } //END "source:"
        }); //END ".autocomplete"

    $("#combobox").combobox();
//THIS IS WHERE IT'S AT!!
//THE DROPDOWNLIST CONTROL SHOULD BE HIDDEN, BUT THIS BUTTON SHOULD TOGGLE ITS CONTENTS INTO VIEW
//Here is the code used in the "combobox" demo provided on the jQuery UI site, but for some reason
//  it doesn't work with mine. The key difference to note is that they created all their DOM
//  elements and attached the listeners etc. using the "(function ($) { });" form.
    $("#toggle").click(function () {
        // close if already visible
        if (input.autocomplete("widget").is(":visible")) {
            input.autocomplete("close");
            return;
        }

        // work around a bug (likely same cause as #5265)
        $(this).blur();

        // pass empty string as value to search for, displaying all results
        input.autocomplete("search", "");
        input.focus();
    });
});

And finally the markup (using the id as the handle)

<form action="#" method="post">
    <h2>Choose your favorite car</h2>
    <hr />
    <div class="ui-widget"> <!-- Autocomplete Combobox -->
        <asp:DropDownList ID="combobox" runat="server" ClientIDMode="Static"></asp:DropDownList><br />
        <input id="autocomplete" class="ui-autocomplete-input ui-widget ui-widget-content ui-corner-left" style="margin-right:0;" />
        <button id="toggle" type="button" tabindex="-1" title="Show All Items" class="ui-button ui-widget ui-state-default ui-button-icon-only ui-corner-right ui-button-icon" role="button" aria-disabled="false" style="margin:0 0 0 -7px;">
            <span class="ui-button-icon-primary ui-icon ui-icon-triangle-1-s"></span><span class="ui-button-text" style="padding:0;">&nbsp;</span>
        </button>
    </div>
</form>

To make it a little more clear, both the button and input objects inside of the combobox ui-widget div should link to the asp.net control. I'm not hard set on the control, but I've tried it both ways and have been unsuccessful.

EDIT: WOOHOOOO!! I made the following change and got the datasource working. Now I just have to fix the button to make it toggle the view of the dropdownlist.

//In the jQuery "source" section I replaced
response(select.children("option").map(function ()
//with
response($("#combobox").children("option").map(function ()
8
  • Are you using a master page? I know that will mess up your IDs. Commented Jul 25, 2011 at 20:16
  • I have ClientIDMode set to "static" so that's not an issue. I learned that the hard way on another problem, lol :) Commented Jul 25, 2011 at 20:26
  • Are you debugging in firebug? Commented Jul 25, 2011 at 20:46
  • I actually use Chrome for development. I really like the "Inspect" feature. The ironic thing, I wired up a jQuery Datepicker in a few minutes, but this blasted combobox is ridiculous :( Commented Jul 25, 2011 at 21:01
  • Firefox has the same feature, but I think there is a firebug plug-in for Chrome. It is just astronomically helpful to be able debug your javascript. Commented Jul 25, 2011 at 21:02

1 Answer 1

1

Here's my solution which I resolved a few months ago and just now have time to post it. In the future I hope to revise this Javascript to support option groups :)

Basically I shoved all my JS off into a separate file and called my custom function passing in the DropDownList and TextBox for each respective Combobox I wanted to create. The DataSourceID was supplied to the DropDownList using an SqlDataSource to populate it from my database. ASP.NET renders this as a <select> element with an <option> element for each ListItem in the DropDownList. The jQuery UI autocomplete plugin reads these <option> elements and creates a hidden <ul> with a <li> for each corresponding <option> in the <select> element. The items are found by the line response($(ddl).children("option").map(function () {.... Note that replacing 'children' with 'find' will return options inside of an <optgroup> tag as well.

Following is my markup which calls the JS function, followed by the JS function itself:

<!-- Head section -->
<script type="text/javascript">
    function pageLoad() {
        cbsetup("#TextBoxID", "#DropDownBoxID");
    });
</script>

<!-- Body section - SAMPLE COMBOBOX -->
<span>
    <asp:DropDownList ID="DropDownBoxID" runat="server" DataSourceID="SDS"
        DataTextField="Name" DataValueField="ID"></asp:DropDownList>
    <asp:TextBox ID="TextBoxID" runat="server" CssClass="combobox
        ui-autocomplete-input ui-widget ui-widget-content ui-corner-left"></asp:TextBox>
    <!-- I know the button code is particularly nasty, no thanks to jQuery UI.
        I just copy/pasted for the most part -->
    <button id="ButtonID" type="button" tabindex="-1" title="Show All Items"
        class="toggle ui-button ui-widget ui-state-default ui-button-icon-only
        ui-corner-right ui-button-icon" role="button" aria-disabled="false"
        style="margin:0 0 0 -5px; height: 23px;">
        <span class="ui-button-icon-primary ui-icon ui-icon-triangle-1-s"></span>
        <span class="ui-button-text" style="padding:0;">&nbsp;</span>
    </button>
</span>
function cbsetup(cb, ddl) {
    try {
        $(cb).unbind();
        $(cb).autocomplete({
            delay: 300,
            minLength: 0,
            autoFocus: true,
            source: function (request, response) {
                var matcher = new RegExp($.ui.autocomplete.escapeRegex(request.term), "i");
                response($(ddl).children("option").map(function () {
                    var text = $(this).text();
                    if (this.value && (!request.term || matcher.test(text)))
                        return {
                            label: text.replace(
                                new RegExp(
                                    "(?![^&;]+;)(?!<[^<>]*)(" +
                                    $.ui.autocomplete.escapeRegex(request.term) +
                                    ")(?![^<>]*>)(?![^&;]+;)", "gi"
                                ), "$1" //"<style=\"text-weight:bold;\">$1</style>"
                                ),
                            value: text,
                            option: this
                        };
                }));
            },
            select: function (event, ui) {
                ui.item.option.selected = true;
            },
            change: function (event, ui) {
                if (!ui.item) {
                    var matcher = new RegExp("^" + $.ui.autocomplete.escapeRegex($(this).val()) + "$", "i"),
                                        valid = false;
                    select.children("option").each(function () {
                        if ($(this).text().match(matcher)) {
                            this.selected = valid = true;
                            return false;
                        }
                    });
                    if (!valid) {
                        // remove invalid value, as it didn't match anything
                        $(this).val("");
                        select.val("");
                        input.data("autocomplete").term = "";
                        return false;
                    }
                }
            }
        });

        $(cb).siblings("button.toggle").click(function () {
            // close if already visible
            if ($(cb).autocomplete("widget").is(":visible")) {
                $(cb).autocomplete("close");
                return;
            }

            // work around a bug (likely same cause as #5265)
            $(this).blur();

            // pass empty string as value to search for, displaying all results
            $(cb).autocomplete("search", "");
            $(cb).focus();
        });
    } /* TRY END */
    catch (e) { jAlert(e.name + ', ' + e.message, 'JS Exception Caught'); }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.