FoxHound
FoxHound

Reputation: 404

jQuery UI Combobox clear selection event

I have a combo box of which the HTML looks like this:

<select id="myCombo">
  <option value=""></option> <!-- Not shown in jQuery UI Combobox because empty value -->
  <option value="1">Option 1</option>
  <option value="2">Option 2</option>
  <option value="3">Option 3</option>
</select>

I've attached the jQuery UI Combobox to I as such:

$("#myCombo").combobox({
    select: function () {
        if ($("#myCombo").val() == "") {
            //DO SOMETHING
        }
        else {
            //DO SOMETHING ELSE
        }
    }
});

When I select an option by either typing and/or selecting an option, the "DO SOMETHING ELSE" part is triggered like it should, so no issue there.

However, when I clear the selection (this selects the first option of my original combo) by deleting the text or clicking the "x", nothing get's triggered, so I can't execute the "DO SOMETHING" part of my function.

How can I trigger this part? Is there maybe another event that is triggered when clearing a selection?

I have searched and found lots of topic on selecting an item, but none on clearing/deselecting something(that were answered at least).

Upvotes: 2

Views: 7021

Answers (5)

CoderA
CoderA

Reputation: 21

So there are many examples on here of how to do this, but they are all (my opinion) cumbersome. You can clear the selection much easier by doing the following:

1) your _createAutocomplete: function() needs to have the following:

.attr( "title", "mytitle" )

Use any title that you want, or set another attribute (name, id etc)- I just happened to have a use for the title, so this worked for me.

2) whatever function you are running only needs the following to clear:

$("input[title='mytitle']").val('');
$("#combobox").val('');

(You have to clear both).

My need was a form with one of the fields being an autocomplete with minimum number of characters. There's an add entry button that submits, refreshes the entry list and resets the form line for additional entries. Much cleaner.

Upvotes: 0

Ben Erwin
Ben Erwin

Reputation: 9

I had spent what felt like a lot of time trying proposed solutions for this and those did not work for me, then I solved it myself.

Look for the _createAutocomplete function where you created your combobox instance. Look for the chain of properties being set to this.input. Then add

.on("focus",function(){
     $(this).val('');
})

Anywhere in the chain.

Upvotes: 1

FoxHound
FoxHound

Reputation: 404

After looking further into it I've found a way to trigger an event when clearing the text.

For this I had to edit the original custom.combobox widget JS, provided by the example on the jQuery UI site

In this js look for the _removeIfInvalid function and edit it like so

_removeIfInvalid: function (event, ui) {

        // Selected an item, nothing to do
        if (ui.item) {
            return;
        }

        // Search for a match (case-insensitive)
        var value = this.input.val(),
          valueLowerCase = value.toLowerCase(),
          valid = false;
        this.element.children("option").each(function () {
            if ($(this).text().toLowerCase() === valueLowerCase) {
                this.selected = valid = true;
                return false;
            }
        });

        // Found a match, nothing to do
        if (valid) {

            //**ADD this piece of code**
            this._trigger("change", event, {
                item: null
            });

            return;
        }

        // Remove invalid value
        this.input
          .val("")
          .attr("title", value + " didn't match any item")
          .tooltip("open");
        this.element.val("");
        this._delay(function () {
            this.input.tooltip("close").attr("title", "");
        }, 2500);
        this.input.data("ui-autocomplete").term = "";

        //**ADD this piece of code**
        this._trigger("change", event, {
            item: null
        });

    }

The added piece of code (I know it's added 2 times, but the code would otherwise jump out of the function before it was ran), will add a change event to the combobox that can be used in your own script. This change event, I can use to run any code I want when the selection is cleared.

$("#myCombo").combobox({
    select: function () {
        //DO SOMETHING ON SELECT

        //IMPORTANT: The other function can't be triggered before the combobox loses focus!!
        $(".custom-combobox-input").blur();
    },
    change:function () {
        //DO SOMETHING ON CLEAR
    }
});

The removeIfInvalid function is always called by default when an option can't be found and by adding an event to the control when this function is invoked is invoked, we finally have a place to execute our algorithmns.

Hopefully, more people are helped with this small fix.

Upvotes: 2

CleanerCoder
CleanerCoder

Reputation: 43

This can be accomplished with select2.

$("#myCombo").select2({
    placeholder: "Select report type",
    allowClear: true,
});
$("#myCombo")
    .on("select2-selecting", function(e) {
        log("selecting val=" + e.val + " choice=" + JSON.stringify(e.choice));
    })
    .on("select2-removed",   function(e) {
        log("removed");
    })

Upvotes: 2

gabor
gabor

Reputation: 450

Empty value cannot be selected in the browser. Hence select() is never called on empty contents.

If you try this, it becomes a bit more clear:

<select id="myCombo">
    <option value=""></option> <!-- Not shown in jQuery UI Combobox because empty value -->
    <option value="1">Option 1</option>
    <option value="2">Option 2</option>
    <option value="3">Option 3</option>
    <option value="4"></option>
    <option value="5">Option 5</option>
</select>

I have slightly modified the javascript, note that I'm empty is never logged.

$("#myCombo").combobox({
    select: function(event, ui) {
        var idx = $("#myCombo").val();
        var txt = $("#myCombo option:selected").text();
        alert(idx);
        if (idx === undefined) {
            console.log("select: I'm empty");
        } else {
            console.log("select: " + idx + ": " + txt);
        }
    }
});

Interestingly, none of the other callbacks (search(), change(), response(), focus()) seems to function from autocomplete, so there is no way to detect a zero-ing out of the select.

Upvotes: 1

Related Questions