我想在select2
中设置初始值,但是如果没有初始值,我想设置占位符而不是值。这是我的代码:
Javascript:
$(".neighborhood").select2({
language: "en",
placeholder: "Find your region ...",
allowClear: true,
data: $scope.regions,
initSelection: function(element, callback) {
var userNeighborhood = $cookies.get("neighborhoodInfo");
if (!isUndefinedOrNull(userNeighborhood)) {
console.log('user neighborhood is not null or undefined');
userNeighborhood = userNeighborhood.split(',');
var initialVal = {
'text': userNeighborhood[0],
'id': userNeighborhood[1],
};
callback(initialVal);
} else {
console.log('user neighborhood is null or undefined ');
}
}
});
var isUndefinedOrNull = function(val) {
return angular.isUndefined(val) || val === null
};
HTML:
<select class="neighborhood js-states form-control" >
<option value=""></option>
</select>
每当 userNeighborhood 不为null或未定义时, select2 的输入将被属性值替换。实际上,当 userNeighborhood 未定义时,它不会设置占位符。
如何解决?
答案 0 :(得分:0)
<select class="neighborhood js-states form-control" data-placeholder="Your Placeholder" >
$('.neighborhood').select2({
minimumResultsForSearch: -1,
placeholder: function(){
$(this).data('placeholder');
}
});