Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic select2 not firing change event

I have a form with a couple of selects inside. I'm applying the select2 jquery plugin over those selects like this:

$("select.company_select, select.positions_select").select2();

The select's work fine, but I have this code to autosubmit my form (I have the autosubmit class on the form tag).

var currentData;
    $('.autosubmit input, .autosubmit select, .autosubmit textarea').live('focus', function () {
        currentData = $(this).val();
    });

    $('.autosubmit input, .autosubmit select, .autosubmit textarea').live('change', function () {
        console.log('autosubmiting...');
        var $this = $(this);
        if (!currentData || currentData != $this.val()) {
            $($this.get(0).form).ajaxSubmit(function (response, status, xhr, $form) {
                currentData = "";
            });
        }
    });

The thing is that with the select2, the change or the focus event doesn't fire at all. If I remove the select2, then the events get fired perfectly.

What am I doing wrong?

like image 335
Phoenix_uy Avatar asked Apr 17 '13 13:04

Phoenix_uy


1 Answers

Select2 has only 2 events, open and change (http://select2.github.io/select2/#events), you are able to add listeners only to them. You can use open event instead of focus for <select> element. And please don't use live() method, as it is deprecated. Use on() instead.

var currentData;
$(".autosubmit select").on("open", function() {
    currentData = $(this).val();
});
$(".autosubmit input").on("focus", function() {
    currentData = $(this).val();
});
$(".autosubmit input, .autosubmit select").on("change", function() {
    var $this = $(this);
    console.log('autosubmitting');
    if (!currentData || currentData != $this.val()) {
        $($this.get(0).form).ajaxSubmit(function (response, status, xhr, $form) {
            currentData = "";
        });
    }
});

Here is the Fiddle

like image 96
Mikhail Chernykh Avatar answered Nov 08 '22 08:11

Mikhail Chernykh