动态选择2不发射更改事件 [英] Dynamic select2 not firing change event
问题描述
我正在应用select2 jquery插件在这些选择:
$(select.company_select,select .positions_select)SELECT2();
选择的工作正常,但我有这个代码自动提交我的表单(我有autosubmit类表单标签)。
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) ).ajaxSubmit(function(response,status,xhr,$ form){
currentData =;
});
}
});事实是,使用select2,更改或焦点事件根本不会触发。如果我删除了select2,那么这个事件就会被完全触发。
我做错了什么?
解决方案Select2只有2个事件,
打开
和更改
( http://select2.github.io/select2/#events ),您只能将侦听器添加到他们。
您可以使用打开
事件而不是焦点
为< select>
元素。
请不要使用live()
方法,因为它已被弃用。在()。
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 =;
});
}
});
这是小提琴
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?
解决方案Select2 has only 2 events,
open
andchange
(http://select2.github.io/select2/#events), you are able to add listeners only to them. You can useopen
event instead offocus
for<select>
element. And please don't uselive()
method, as it is deprecated. Useon()
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
这篇关于动态选择2不发射更改事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!