问题
I'm using Select2 to create a Gmail-style e-mail addresses field in my application. It works great except for one case: when the user types in an e-mail address and doesn't put a space or comma after it, and doesn't hit enter or tab. For example, if they just type an e-mail address and then use the mouse to select the next field in the form, the e-mail address they typed goes away.
I have an example jsfiddle here that illustrates the problem.
Here's how I'm setting up select2 on my hidden input:
$(function(){
$('input').select2({
tags: [],
width: "300px",
dropdownCss: {display: 'none'},
tokenSeparators: [',', ', ', ' ']
});
});
Is there a way for me to set up select2 so that onBlur it just takes whatever is left and is not currently a tag and makes it one?
回答1:
This is now supported in version 3.3 of the select2 library using the 'selectOnBlur' option.
回答2:
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.
回答3:
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.
回答4:
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.
来源:https://stackoverflow.com/questions/13820718/jquery-select2-tag-on-blur