jQuery Select2 Tag on Blur

蓝咒 提交于 2019-12-05 02:53:18

This is now supported in version 3.3 of the select2 library using the 'selectOnBlur' option.

I had a form with select2 (tag mode) and a submit button. By default when user types a tag, without selecting the tag from drop down or pressing one of triggering control keys, the user entry will be lost because plugin closes the generated input dom object on blur event.

My quick fix to this problem was to hack the plugin blur function and to add the following lines:

var val=this.search.val();
if($.trim(val)!='') this.onSelect({id:val,text:val});

Once blur function is called, the above code checks if user entry. If there's any it triggers select event and sends the required object. The object i'm passing is suitable only for select2 in tagging mode and if you use select2 v3.2 this line can be inserted at start of blur function of AbstractSelect2 on line 1311. I hope this gives you an idea on how to customize the widget according to your needs.

From the documentation as of 4.0.3:

$('select').select2({
  selectOnClose: true
});

This will capture the selection and create a tag if the user clicks elsewhere.

I dont really understood what you are trying to do here because you are speaking about emails:

jQuery(element.val().split(",")).each(function () {
                data.push({id: this, text: this});
            });

But you could try this instead:

var splitted = element.val().split(",");
for(var i=0,z=splitted.length;i<z;i++)
    data.push({id: splitted[i], text: splitted[i]});

By the way, your jsfiddle is uncomplete.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!