Dynamic select2 not firing change event
Asked Answered
O

1

25

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?

Overfly answered 17/4, 2013 at 13:56 Comment(0)
P
33

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

Proteinase answered 17/4, 2013 at 14:14 Comment(2)
had the same problem tonight. this almost worked for me. using jQuery 1.11.1 and a text box version of select2 I had to use the longer form of $('.container').on('change', '#myselect2', function() { ...Lytle
This fiddle no longer appears to work. I'm seeing "Uncaught TypeError: $(...).select2 is not a function" in the console despite select2.js being included in the external resources. Possibly a problem with jsfiddle?Alyssa

© 2022 - 2024 — McMap. All rights reserved.