我正在工作Select2
选择框。
占位符未显示在select2
中。始终显示select2
中选择的第一个选项。它会自动选择我想要显示占位符的第一个选项而不是它。
脚本:
<script type="text/javascript">
$(document).ready(function () {
var data = $('#test_skill').select2({
placeholder: "Please select an skill",
allowClear: true
});
});
// I have also tried this: This is also not working
$('#test_skill').select2({
placeholder: {
id: '-1', // the value of the option
text: 'Please select an skill'
}
});
</script>
HTML:
<select class="skills_select2" required name="test_skill" id="test_skill">
<option value="1">TEST1</option>
<option value="2">TEST2</option>
<option value="3">TEST3</option>
</select>
答案 0 :(得分:18)
只需将<option></option>
放在首位选择:
$(document).ready(function() {
$selectElement = $('#test_skill').select2({
placeholder: "Please select an skill",
allowClear: true
});
});
&#13;
.skills_select2 {
width: 120px;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.css" />
<select class="skills_select2" required name="test_skill" id="test_skill">
<option></option>
<option value="1">TEST1</option>
<option value="2">TEST2</option>
<option value="3">TEST3</option>
</select>
&#13;
答案 1 :(得分:3)
要使占位符正常工作,您必须添加一个空选项(即)作为查看占位符的第一个元素。
来自Select2文档:
&#34;请注意,因为浏览器假定在非多值选择框中选择了第一个选项元素,所以必须提供空的第一个选项元素()以使占位符起作用。&#34;
例如:
<select class="skills_select2" required name="test_skill" id="test_skill">
<option></option>
<option value="1">TEST1</option>
<option value="2">TEST2</option>
<option value="3">TEST3</option>
</select>
和javascript将是:
$("#test_skill").attr(
"data-placeholder","Please select an skill"
);
答案 2 :(得分:2)
如何在html中设置
<select>
<option value="" disabled selected>Select your option</option>
<option value="your value ">your value</option>
</select>
答案 3 :(得分:1)
对我来说最好的方法是设置如下: 取消对数据/结果的第一个值,并在select2
中设置占位符$.ajax({
url: 'api/v1/users',
type: 'GET',
success: function(response) {
let data = $.map(response, function(responseData) {
return {
id: responseData.id,
text: responseData.name
}
});
const selectedElement = $('#user_id');
selectedElement.html('');
data.unshift({id: -1, text: '', selected: 'selected', search:'', hidden:true });
selectedElement.select2({
theme: 'bootstrap',
data: data,
placeholder: {
id: "-1",
text: '--- Please select a user ---',
selected:'selected'
}
});
答案 4 :(得分:0)
萨拉姆。
覆盖templateSelection
可解决问题:
templateSelection: function(item) {
return item.name // "name" property of received data from ajax
|| item.text; // "text" value of default selected option or placeholder text
}