jquery UI Combobox ONCHANGE
Asked Answered
A

8

35

how can I attach an onchange function in a jqueryUI combobox? Here is my code:

$(".cmbBox").combobox({
     change:function(){
         alert($(this).val());
     }
});

When the value changes, it will alert the updated value.

Any help please.. :)

Asp answered 21/1, 2011 at 15:3 Comment(3)
Which combobox? Kindly provide the URL for the specific one you are using.Harman
jqueryui.com/demos/autocomplete/#combobox this one.. the combobox submenu sir..Asp
In fact, there's already a "hook" for the onchange event. Look for autocompletechange. That's what I used and it works fine! I added a answer that match with this commentEctoblast
P
51

The combobox example source is all right there in the example. I'd trigger the change event of the underlying select by modifying the source code like this (changing the select event handler inside autocomplete initialization inside the plugin):

/* Snip */
select: function( event, ui ) {
    ui.item.option.selected = true;
    self._trigger( "selected", event, {
        item: ui.item.option
    });
    select.trigger("change");                            
},
/* Snip */

and then define an event handler for the regular change event of the select:

$(".cmbBox").change(function() {
    alert(this.value);
});

Unfortunately this won't work exactly the same way as the normal select.change event: it will trigger even you select the same item from the combobox.

Try it out here: http://jsfiddle.net/andrewwhitaker/hAM9H/

Pignut answered 21/1, 2011 at 17:25 Comment(7)
Very nice! That is exactly what I was thinking, though I got confused by the line above "._trigger", I thought this was the way to trigger events. Is "trigger" an javascript or jQuery Method? ThanksMaternal
@ClayBoom: Good question-- self._trigger is an internal jqueryUI function (github.com/jquery/jquery-ui/blob/master/ui/…) that autocomplete uses.Pignut
Thanks! I was just wondering the difference between _trigger and trigger because both are used in this context.Maternal
I had to replace "self" with "that" so that this snippet would work. and even then, it only catched changes that were the result of selecting from the drop-down list but not from the free-text. eventually I only added to the "change:" function below the "select:" in combobox.js this>>>select.trigger("change");<<< and now it catches all sort of changes.Robedechambre
+1 for the jsfiddle link. The jeasyui.com site is a start, but there aren't anywhere near enough examples on there. I can't find a single one that doesn't use 'easyui-combobox' for the creation...Dissemble
Unless I'm doing something wrong, this code no longer works with the most recent version of the combobox code. I get the error Uncaught ReferenceError: select is not defined when I try to use this.Naomanaomi
@Naomanaomi I'm not sure what's happening on your code, but check out the last comments on this answer, might be the case https://mcmap.net/q/428925/-jquery-ui-autocomplete-combobox-with-categoriesKostival
B
25

IMHO, an even simpler way to detect the user has changed the combobox (without having to tweak the jQuery UI autocomplete combobox source code) is as follows; this works for me. It's repetitious if you've got lots of them, though surely there's a way to refactor. Thanks to all who have studied and explained this widget at length, here and elsewhere.

$("#theComboBox").combobox({ 
        select: function (event, ui) { 
            alert("the select event has fired!"); 
        } 
    }
);
Bergsonism answered 25/8, 2013 at 11:39 Comment(3)
This was what I needed. The other method talking about triggers and editing the code didn't work because the source I had was different enough that I couldn't find the right place to add it. But this technique worked great! Thanks.Council
David code is great and it worked for me. Thanks David. Andrew code look pretty decent but I am not sure why it did not work for me.Intemerate
Not working for me : $("#productList").combobox({ url: 'productList', valueField:'code', textField:'code', editable:false, select: function (event, ui) { alert("the select event has fired!"); } });Premillenarian
F
1

Into the ui.combobox plugin :

i added at the end of the select method :

$(input).trigger("change", ui);

i added before the "var input ..." :

select.attr('inputId', select.attr('id') + '_input');

after, to have a functional onchange event... on ui.combobox i commented the change method and moved its code to the checkval method that extends ui.autocomplete :

$.extend( $.ui.autocomplete, {
    checkVal: function (select) {
            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("");
                $(this).data("autocomplete").term = "";
                $(this).data("autocomplete").close();
            }
        }
});

and i coded the input change method as below :

var oCbo = ('#MyCbo').combobox();
$('#' + oCbo.attr('inputId')).change(function () {

    // from select event : check if value exists
    if (arguments.length < 2) {
        $.ui.autocomplete.checkVal.apply(this, [oCbo]);
    }

        // YOUR CODE HERE
});
Flop answered 16/4, 2012 at 11:56 Comment(0)
C
1
$("#theComboBox").combobox({ 
    select: function (event, ui) { 
        alert("the select event has fired!"); 
    } 
}

);

Chantell answered 21/1, 2014 at 5:51 Comment(1)
This is exactly the same code as suggested by David Barrows 5 months previously.Speech
C
0

It says in the "Events" section of the documentation, that you handle a change like this...

$( ".selector" ).autocomplete({
   change: function(event, ui) { ... }
});
Carmel answered 21/1, 2011 at 15:47 Comment(0)
C
0

This seems to work for me

if('function' == typeof(callback = ui.item.option.parentElement.onchange))
                        callback.apply(this, []);

just before

self._trigger("selected", event, {
Crosscountry answered 27/1, 2012 at 0:11 Comment(0)
A
0

simplest way (IMHO), if you are deploying combobox as widget:

  1. find "_create" method in widget

  2. inside of it look for "autocomplete" (where input is managed)

  3. add (use) "select" method to get your data: ui.item.value


(function($){
$.widget( "ui.combobox", {
    // default options
    options: {
    //your options ....
    },
    _create: function() {

    //some code ....

    //this is input you look for
    input = $( "" )
    .appendTo( wrapper )
    .val( value )
    .addClass( "ui-state-default" )

    //this is autocomplete you look for
    .autocomplete({
        delay: 0,
        minLength: 0,
        source: function( request, response ) {
        //some code ...
        },

        //this is select method you look for ...
        select: function( event, ui ) {

        //this is your selected value
        console.log(ui.item.value);
        },
        change: function( event, ui ) {

        //some code ...
        }
    })
    //rest of code
    },

    destroy: function() {
    this.wrapper.remove();
    this.element.show();
    $.Widget.prototype.destroy.call( this );
    }
});
Archiepiscopate answered 26/4, 2013 at 8:57 Comment(0)
E
0

In fact, there's already a "hook" for the onchange event.

Just change the following line for the method call or the callback that you want:

autocompletechange: "_removeIfInvalid"
Ectoblast answered 8/1, 2014 at 17:1 Comment(1)
Can you give an example where you change the above so it will trigger an alert? or a function that triggers an alert?Edithe

© 2022 - 2024 — McMap. All rights reserved.