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.. :)

Andrew Whitaker
  • 124,656
  • 32
  • 289
  • 307
Vincent Dagpin
  • 3,581
  • 13
  • 55
  • 85
  • Which combobox? Kindly provide the URL for the specific one you are using. – karim79 Jan 21 '11 at 15:10
  • http://jqueryui.com/demos/autocomplete/#combobox this one.. the combobox submenu sir.. – Vincent Dagpin Jan 21 '11 at 15:22
  • 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 comment – Thermech Jan 08 '14 at 17:02

8 Answers8

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/

Andrew Whitaker
  • 124,656
  • 32
  • 289
  • 307
  • 1
    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? Thanks – ClayKaboom Jul 21 '11 at 13:24
  • 1
    @ClayBoom: Good question-- `self._trigger` is an internal jqueryUI function (https://github.com/jquery/jquery-ui/blob/master/ui/jquery.ui.widget.js#L348) that autocomplete uses. – Andrew Whitaker Jul 21 '11 at 13:50
  • Thanks! I was just wondering the difference between `_trigger` and `trigger` because both are used in this context. – ClayKaboom Jul 21 '11 at 13:57
  • 1
    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. – Nir O. Oct 26 '12 at 17:39
  • +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... – Beachhouse Dec 05 '12 at 20:08
  • 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. – Nate Oct 25 '13 at 22:01
  • @Nate I'm not sure what's happening on your code, but check out the last comments on this answer, might be the case http://stackoverflow.com/a/11042693/1067465 – Fernando Silva Jan 24 '14 at 10:25
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!"); 
        } 
    }
);
David Barrows
  • 758
  • 7
  • 20
  • 2
    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. – Ted Nov 20 '13 at 22:39
  • 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. – Kurkula Feb 20 '14 at 21:01
  • Not working for me : `$("#productList").combobox({ url: 'productList', valueField:'code', textField:'code', editable:false, select: function (event, ui) { alert("the select event has fired!"); } });` – Neeraj Jain Mar 30 '17 at 12:14
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
});
ccyborg
  • 11
  • 2
1
$("#theComboBox").combobox({ 
    select: function (event, ui) { 
        alert("the select event has fired!"); 
    } 
}

);

Jagdish
  • 19
  • 1
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 );
    }
});
Jeffz
  • 2,075
  • 5
  • 36
  • 51
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"
Thermech
  • 4,371
  • 2
  • 39
  • 60
0

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

$( ".selector" ).autocomplete({
   change: function(event, ui) { ... }
});
JasCav
  • 34,458
  • 20
  • 113
  • 170
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, {
Oscar Nevarez
  • 994
  • 12
  • 24