snark17
snark17

Reputation: 399

Select2 Options different from value that is returned

I have a set of objects (in JSON form) that have an ID and description.

I need the user to be able to see at the ID or description in the drop down menu, but when they select the ID or description, the object's ID must be returned.

An object looks something like this:

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

In the drop-down menu, I want both 100 and George Washington to appear. When the user selects either of these, I want to return 100. Any thoughts on how to implement this behavior?

Upvotes: 2

Views: 551

Answers (2)

gaetanoM
gaetanoM

Reputation: 42054

You may change the data to pass to the select2 in order to have double elements: the first showing the id and the second the name or description, both with the same 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>

Upvotes: 1

SamGhatak
SamGhatak

Reputation: 1493

You can find one simple implementation at this fiddle: https://jsfiddle.net/2j8e5ugd/

basically you need to iterate over the json and add data to the select list.

HTML

<select id='s1'>

</select>

Script

$(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}));
  }
});

Hope it helps

Upvotes: 0

Related Questions