使用 select2 用多维数组中的数据填充下拉列表

我发送两个属性的响应数据如下:


response["gender"] = 'Male' #Or whatever is the value from database

response["gender_choices"] = [

  [, '-----------------'],

  ['MALE', 'Male'],

  ['FEMALE', 'Female'],

  ['OTHERS', 'Others']

]

我在用select2。我现在的代码如下:


$('.element-form#gender').select2({

    placeholder: "Gender",

    data: $.map(response.gender_choices, function(obj){

        obj.value = obj[0];

        obj.text = obj[1];

        return obj.value, obj.text;

      }

    ),

});

但它正在将obj.text值添加到选项 value和text。我想要的是将的值添加obj.value到option value和obj.texttext 。另外我怎样才能使response["gender"]选项选定值?


隔江千里
浏览 138回答 1
1回答

侃侃无极

您可以用于.val(yourgendertobeselected)设置 select-box 的选定值。此外,您需要用于.trigger('change')将此更改更新为 select-box 。然后,为了设置value和text使用id&text并在那里添加值,即 : item[0],item[1],..etc。演示代码:var response = {&nbsp; "gender": "Male",&nbsp; "gender_choices": [&nbsp; &nbsp; ['', '-----------------'],&nbsp; &nbsp; ['MALE', 'Male'],&nbsp; &nbsp; ['FEMALE', 'Female'],&nbsp; &nbsp; ['OTHERS', 'Others']&nbsp; ]}$('#gender').select2({&nbsp; placeholder: "Gender",&nbsp; data: $.map(response.gender_choices, function(item) {&nbsp; &nbsp; return {&nbsp; &nbsp; &nbsp; text: item[0], //option text(MALE,FEMALE..)&nbsp; &nbsp; &nbsp; id: item[1] //option value(male,female..)&nbsp; &nbsp; }&nbsp; }),&nbsp; 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>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript