2017-01-08 55 views
1

我有一組具有ID和說明的對象(採用JSON格式)。Select2與返回的值不同的選項

我需要用戶能夠在下拉菜單中看到ID或說明,但是當他們選擇ID或說明時,必須返回對象的ID。

的對象看起來是這樣的:

{ 
"id": 100 
"name": "George Washington" 
"description": "The first president of the United States." 
} 

在下拉菜單中,我想這兩個100George Washington出現。當用戶選擇其中之一時,我想返回100。有關如何實現此行爲的任何想法?

+0

看看https://select2.github.io/options.html#templateSelection – ValLeNain

回答

0

您可以在此找到小提琴一個簡單的實現: https://jsfiddle.net/2j8e5ugd/

基本上你需要遍歷JSON和數據添加到選擇列表中。

HTML

<select id='s1'> 

</select> 

腳本

$(document).ready(function(){ 
    var data = [{ 
    "id": 100, 
    "name": "George Washington", 
    "description": "The first president of the United States." 
    },{ 
    "id": 101, 
    "name": "George Washington2", 
    "description": "The first president of the United States." 
    }] 
    //fetch your data in this data variable 
    for(var i = 0; i<data.length; i++){ 
     $('#s1').append($('<option>', {value:data[i].id, text:data[i].id})); 
    $('#s1').append($('<option>', {value:data[i].id, text:data[i].name})); 
    } 
}); 

希望它可以幫助

0

您可以更改數據傳遞給選擇2以具有雙重要素:第一顯示id和第二個名稱或描述,兩者都具有相同的ID。

var data = [{ 
 
    "id": 100, 
 
    "name": "George Washington", 
 
    "description": "The first president of the United States." 
 
}, { 
 
    "id": 101, 
 
    "name": "1111", 
 
    "description": "111111111111." 
 
}]; 
 

 
// convert your input data 
 
var result = []; 
 
data.forEach(function(obj, idx) { 
 
    result.push({id: obj.id, text: obj.id}) 
 
    result.push({id: obj.id, text: obj.name}); 
 
}); 
 

 
$(".js-example-data-array").select2({ 
 
    data: result 
 
}).on('change', function(e) { 
 
    console.log('Selected: ' + this.value); 
 
}).trigger('change')
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<link rel="stylesheet" href="https://rawgit.com/select2/select2/master/dist/css/select2.min.css"> 
 
<script src="https://select2.github.io/dist/js/select2.full.js"></script> 
 

 
<select class="js-example-data-array"></select>