1 回答
TA贡献2051条经验 获得超10个赞
您可以用于.val(yourgendertobeselected)设置 select-box 的选定值。此外,您需要用于.trigger('change')将此更改更新为 select-box 。然后,为了设置value和text使用id&text并在那里添加值,即 : item[0],item[1],..etc。
演示代码:
var response = {
"gender": "Male",
"gender_choices": [
['', '-----------------'],
['MALE', 'Male'],
['FEMALE', 'Female'],
['OTHERS', 'Others']
]
}
$('#gender').select2({
placeholder: "Gender",
data: $.map(response.gender_choices, function(item) {
return {
text: item[0], //option text(MALE,FEMALE..)
id: item[1] //option value(male,female..)
}
}),
width: "100px"
});
var selected = response.gender //gendere to set
$('#gender').val(selected).trigger('change'); //set gender selected
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://rawgit.com/select2/select2/master/dist/css/select2.min.css">
<script src="https://rawgit.com/select2/select2/master/dist/js/select2.js"></script>
<select id="gender"></select>
添加回答
举报