Handling jQuery Dropdown Values on Change Event

Introduction

In web development, managing dropdown menus and capturing user interactions is a common task. This tutorial focuses on handling change events for jQuery-based dropdowns, specifically using the jQuery UI Autocomplete widget to enhance select elements. We’ll explore how to capture values from multiple dropdowns when their selections change.

Prerequisites

  • Basic knowledge of HTML and JavaScript.
  • Familiarity with jQuery and its plugins, particularly jQuery UI.
  • A text editor or IDE for writing code.

Setting Up the Environment

First, ensure you have included jQuery and jQuery UI libraries in your project. You can include them via CDN:

<head>
    <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
    <script src="//code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="//code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>
</head>

Creating the Dropdown Elements

We will use two dropdowns, enhanced with jQuery UI’s Autocomplete widget. Here is a simple HTML setup:

<div class="ui-widget">
    <select id="pick">
        <option value="">Select one...</option>
        <option value="1">1</option>
        <option value="2">2</option>
        <option value="3">3</option>
        <option value="4">4</option>
    </select>

    <select id="drop">
        <option value="">Select one...</option>
        <option value="11">11</option>
        <option value="12">12</option>
        <option value="13">13</option>
        <option value="14">14</option>
    </select>
</div>

Initializing the Autocomplete Widget

To enhance these dropdowns with autocomplete functionality, we initialize them using jQuery UI’s combobox widget:

(function($) {
    $.widget("ui.combobox", {
        _create: function() {
            var self = this,
                select = this.element.hide(),
                selected = select.children(":selected"),
                value = selected.val() ? selected.text() : "";

            var input = this.input = $("<input>").insertAfter(select).val(value).autocomplete({
                delay: 0,
                minLength: 0,
                source: function(request, response) {
                    var matcher = new RegExp($.ui.autocomplete.escapeRegex(request.term), "i");
                    response(select.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"), "<strong>$1</strong>"),
                                value: text,
                                option: this
                            };
                        }
                    }));
                },
                select: function(event, ui) {
                    ui.item.option.selected = true;
                    self._trigger("selected", event, { item: ui.item.option });
                    select.trigger("change");
                },
                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) {
                            $(this).val("");
                            select.val("");
                            input.data("autocomplete").term = "";
                            return false;
                        }
                    }
                }
            }).addClass("ui-widget ui-widget-content ui-corner-left");

            input.data("autocomplete")._renderItem = function(ul, item) {
                return $("<li>").data("item.autocomplete", item).append("<a>" + item.label + "</a>").appendTo(ul);
            };

            this.button = $("<button type='button'>&nbsp;</button>")
                .attr("tabIndex", -1)
                .attr("title", "Show All Items")
                .insertAfter(input)
                .button({
                    icons: { primary: "ui-icon-triangle-1-s" },
                    text: false
                })
                .removeClass("ui-corner-all")
                .addClass("ui-corner-right ui-button-icon")
                .click(function() {
                    if (input.autocomplete("widget").is(":visible")) {
                        input.autocomplete("close");
                        return;
                    }
                    input.autocomplete("search", "");
                    input.focus();
                });
        },

        destroy: function() {
            this.input.remove();
            this.button.remove();
            this.element.show();
            $.Widget.prototype.destroy.call(this);
        }
    });
})(jQuery);

$(function() {
    $("#pick").combobox({
        change: function() {
            alert("First dropdown changed");
        }
    });

    $("#drop").combobox({
        change: function() {
            alert("Second dropdown changed");
        }
    });
});

Handling Change Events

To capture the values from both dropdowns when their selections change, attach a change event handler:

$("#pick").change(function() {
    var start = $(this).val();
    console.log("First dropdown value: ", start);
});

$("#drop").change(function() {
    var end = $(this).val();
    console.log("Second dropdown value: ", end);
});

Conclusion

This tutorial demonstrated how to enhance HTML select elements with jQuery UI’s Autocomplete widget and capture their values on change. By using the combobox widget, we created interactive dropdowns that provide a richer user experience. You can further customize these widgets to suit your application’s needs.

Leave a Reply

Your email address will not be published. Required fields are marked *