I am using select2 jquery plugin from http://ivaynberg.github.io/select2/.
我正在使用来自http://ivaynberg.github.io/select2/的select2 jquery插件。
I am using following code.
我正在使用以下代码。
$(document).ready(function () {
$("#e6").select2({
placeholder: "Search for a movie",
minimumInputLength: 1,
ajax: { // instead of writing the function to execute the request we use Select2's convenient helper
url: "http://api.rottentomatoes.com/api/public/v1.0/movies.json",
dataType: 'jsonp',
quietMillis: 1000,
data: function (term, page) {
return {
q: term, // search term
page_limit: 10,
apikey: "ju6z9mjyajq2djue3gbvv26t" // please do not use so this example keeps working
};
},
results: function (data, page) { // parse the results into the format expected by Select2.
// since we are using custom formatting functions we do not need to alter remote JSON data
return { results: data.movies };
}
},
initSelection: function (element, callback) {
var id = 9942;//$(element).val();
alert('initSelection');
if (id !== "") {
$.ajax("http://api.rottentomatoes.com/api/public/v1.0/movies/" + id + ".json", {
data: {
apikey: "ju6z9mjyajq2djue3gbvv26t"
},
dataType: "jsonp"
}).done(function (data) { callback(data); });
}
},
formatResult: movieFormatResult, // omitted for brevity, see the source of this page
formatSelection: movieFormatSelection, // omitted for brevity, see the source of this page
dropdownCssClass: "bigdrop", // apply css that makes the dropdown taller
escapeMarkup: function (m) { return m; } // we do not want to escape markup since we are displaying html in results
});
});
$(document).ready(function () {
$("#e6").on("select2-selecting", function (e) {
var v = 10;
alert("selecting val=" + e.val + " choice=" + JSON.stringify(e.choice));
var id = document.getElementById('<%= savebtn.ClientID %>');
id.value = e.val;
id.click();
});
});
Problem: For some reasons initSelection is not getting called and because of this, I am not able to set value for the textbox across post-backs.
问题:由于某些原因,initSelection没有被调用,因此,我无法跨回发后设置文本框的值。
I am using loading remote data example from http://ivaynberg.github.io/select2/ site.
我正在使用来自http://ivaynberg.github.io/select2/ site的加载远程数据示例。
I looked at the documentation for initSelection and it says "This function will only be called when there is initial input to be processed.", I am not sure what exactly it means.
我查看了initSelection的文档,并说它“只有在有初始输入要处理的时候才会调用此函数。”,我不确定它究竟意味着什么。
Am I doing something wrong? Please help
难道我做错了什么?请帮忙
4 个解决方案
#1
22
You should provide initial value:
你应该提供初始值:
<input ... value="192" ... />
or
$('#e6').select2('val', 192);
For multiple values, either:
对于多个值,可以是:
<input ... value="192,193" ... />
or
$('#e6').select2('val', [192,193]);
See JSFiddle.
#2
6
You can do simply like this if you don't want to use a value by default.
如果您不想在默认情况下使用值,则可以这样做。
$(document).ready(function () {
$("#e6").select2({
...
},
initSelection: function (element, callback) {
...
},
formatResult: movieFormatResult, // omitted for brevity, see the source of this page
formatSelection: movieFormatSelection, // omitted for brevity, see the source of this page
dropdownCssClass: "bigdrop", // apply css that makes the dropdown taller
escapeMarkup: function (m) { return m; } // we do not want to escape markup since we are displaying html in results
}).select2('val', []);
});
Adding select2('val', []);
at the end of declaration solve this problem.
添加select2('val',[]);在声明结束时解决了这个问题。
#3
0
Well this is what I do for more complex situations since -if not controlled- initalvalue gets saved to db (in coffeescript)
这就是我为更复杂的情况所做的事情,因为 - 如果没有被控制 - initalvalue被保存到db(在coffeescript中)
if $("#categories").val().length is 0
$("#categories").val "initialValue"
$("#categories").select2
closeOnSelect:false
containerCssClass: "select2-default"
formatNoMatches: ->
I18n.t "shared.navbar.no_matches_found"
formatInputTooShort: (input, min) ->
I18n.t("shared.navbar.please_select") + " " + (min - input.length) + " " + I18n.t("shared.navbar.more_characters")
formatSelectionTooBig: (limit) ->
I18n.t("shared.navbar.you_can_only_select") + " " + limit + " " + I18n.t("shared.navbar.item") + ((if limit is 1 then "" else "s"))
formatLoadMore: (pageNumber) ->
I18n.t "shared.navbar.loading_more_results"
formatSearching: ->
I18n.t "shared.navbar.searching"
minimumInputLength: 3
width: "100%"
multiple: true
ajax:
url: "/categories/list_styles"
dataType: "json"
quietMillis: 100
data: (term, page) ->
q: term
page_limit: 10
page: page
results: (data) ->
hashtable = {}
results = []
$.each data, (index, item) ->
if hashtable[item.parent] is `undefined`
hashtable[item.parent] =
text: item.parent
children: []
results.push hashtable[item.parent]
hashtable[item.parent].children.push
id: item._id
text: item.title
results: results
initSelection: (element, callback) ->
data1 = []
if element.val() is "initialValue"
element.val('')
jQuery(element.val().split(",")).each ->
$.ajax
type: "get"
url: "/providers/list_categories"
async: false
dataType: "json"
data: { id: $("#provider_id").val(), selected: $("#categories").val().split(",") }
success: (category) ->
$.each category, (i, obj) ->
data1.push
id: @_id
text: @title
callback data1
$.each $(".select2-container"), (i, n) ->
$(n).next().show().fadeTo(0, 0).height("0px").css "left", "auto" # make the original select visible for validation engine and hidden for us
$(n).prepend $(n).next()
$(n).delay(500).queue ->
$(this).removeClass "validate[required]" #remove the class name from select2 container(div), so that validation engine dose not validate it
$(this).dequeue()
#4
0
Use this:
remove the previous options selected options with this:
删除以前选项选择的选项:
arr = json.filter(function( obj ) {
return arrSelectedValues.indexOf(obj.foo) == -1;
});
and create a new element selected:
并创建一个新元素:
option = document.createElement('option');
option.value = 'foo';
option.innerHTML = 'foo';
option.selected = true;
document.getElementById('selectFoobares').appendChild(option);
not the best way but works
不是最好的方式,但工作
#1
22
You should provide initial value:
你应该提供初始值:
<input ... value="192" ... />
or
$('#e6').select2('val', 192);
For multiple values, either:
对于多个值,可以是:
<input ... value="192,193" ... />
or
$('#e6').select2('val', [192,193]);
See JSFiddle.
#2
6
You can do simply like this if you don't want to use a value by default.
如果您不想在默认情况下使用值,则可以这样做。
$(document).ready(function () {
$("#e6").select2({
...
},
initSelection: function (element, callback) {
...
},
formatResult: movieFormatResult, // omitted for brevity, see the source of this page
formatSelection: movieFormatSelection, // omitted for brevity, see the source of this page
dropdownCssClass: "bigdrop", // apply css that makes the dropdown taller
escapeMarkup: function (m) { return m; } // we do not want to escape markup since we are displaying html in results
}).select2('val', []);
});
Adding select2('val', []);
at the end of declaration solve this problem.
添加select2('val',[]);在声明结束时解决了这个问题。
#3
0
Well this is what I do for more complex situations since -if not controlled- initalvalue gets saved to db (in coffeescript)
这就是我为更复杂的情况所做的事情,因为 - 如果没有被控制 - initalvalue被保存到db(在coffeescript中)
if $("#categories").val().length is 0
$("#categories").val "initialValue"
$("#categories").select2
closeOnSelect:false
containerCssClass: "select2-default"
formatNoMatches: ->
I18n.t "shared.navbar.no_matches_found"
formatInputTooShort: (input, min) ->
I18n.t("shared.navbar.please_select") + " " + (min - input.length) + " " + I18n.t("shared.navbar.more_characters")
formatSelectionTooBig: (limit) ->
I18n.t("shared.navbar.you_can_only_select") + " " + limit + " " + I18n.t("shared.navbar.item") + ((if limit is 1 then "" else "s"))
formatLoadMore: (pageNumber) ->
I18n.t "shared.navbar.loading_more_results"
formatSearching: ->
I18n.t "shared.navbar.searching"
minimumInputLength: 3
width: "100%"
multiple: true
ajax:
url: "/categories/list_styles"
dataType: "json"
quietMillis: 100
data: (term, page) ->
q: term
page_limit: 10
page: page
results: (data) ->
hashtable = {}
results = []
$.each data, (index, item) ->
if hashtable[item.parent] is `undefined`
hashtable[item.parent] =
text: item.parent
children: []
results.push hashtable[item.parent]
hashtable[item.parent].children.push
id: item._id
text: item.title
results: results
initSelection: (element, callback) ->
data1 = []
if element.val() is "initialValue"
element.val('')
jQuery(element.val().split(",")).each ->
$.ajax
type: "get"
url: "/providers/list_categories"
async: false
dataType: "json"
data: { id: $("#provider_id").val(), selected: $("#categories").val().split(",") }
success: (category) ->
$.each category, (i, obj) ->
data1.push
id: @_id
text: @title
callback data1
$.each $(".select2-container"), (i, n) ->
$(n).next().show().fadeTo(0, 0).height("0px").css "left", "auto" # make the original select visible for validation engine and hidden for us
$(n).prepend $(n).next()
$(n).delay(500).queue ->
$(this).removeClass "validate[required]" #remove the class name from select2 container(div), so that validation engine dose not validate it
$(this).dequeue()
#4
0
Use this:
remove the previous options selected options with this:
删除以前选项选择的选项:
arr = json.filter(function( obj ) {
return arrSelectedValues.indexOf(obj.foo) == -1;
});
and create a new element selected:
并创建一个新元素:
option = document.createElement('option');
option.value = 'foo';
option.innerHTML = 'foo';
option.selected = true;
document.getElementById('selectFoobares').appendChild(option);
not the best way but works
不是最好的方式,但工作