2017-01-08 6 views
1

IDと説明を持つ一連のオブジェクト(JSON形式)があります。Select2返される値と異なるオプション

IDまたは説明をドロップダウンメニューで表示できるようにする必要がありますが、IDまたは説明を選択するときは、オブジェクトのIDを返す必要があります。私が表示されるように、両方の100George Washingtonをしたい、ドロップダウンメニューで

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

オブジェクトは、次のようになります。ユーザーがこれらのいずれかを選択すると、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})); 
    } 
}); 

あなたは二重の要素を持つためにSELECT2に渡すデータを変更することがあり、それは

0

を役に立てば幸い:最初の同じ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>

関連する問題