Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- $('#contact_id').select2({
- ajax: {
- url: 'example.com/contacts/select',
- dataType: 'json',
- delay: 250,
- data: function (params) {
- return {
- q: params.term,
- page: params.page
- };
- },
- processResults: function (data) {
- return {
- results: data
- };
- },
- cache: true
- },
- minimumInputLength: 3,
- maximumSelectionLength: 1
- });
- foreach($contacts as $con) {
- $results[] = [
- 'id' => $con->contact_id,
- 'text' => $con->full_name,
- 'org' => [
- 'org_id' => $con->organization_id,
- 'org_name' => $con->org_name
- ]
- ];
- }
- return response()->json($results);
- <select>
- <option value="43" data-org="{org_id:377, org_name:'Galactic Empire'}">Darth Vader</option>
- </select>
- processResults: function (data) {
- data = data.map(function (item) {
- return {
- id: item.id_field,
- text: item.text_field,
- otherfield: item.otherfield
- };
- });
- return { results: data };
- }
- var data=$('#contact_id').select2('data')[0];
- console.log(data.otherfield);
- $('#select2-box').select2({
- placeholder: 'Search Existing Contacts',
- ajax: {
- url: '/contacts/typeahead',
- dataType: 'json',
- delay: 250,
- data: function(params){
- return {
- q: params.term,
- type: '',
- suggestions: 1
- };
- },
- processResults: function(data, params){
- //Send the data back
- return {
- results: data
- };
- }
- },
- minimumInputLength: 2
- }).on('select2:select', function(event) {
- // This is how I got ahold of the data
- var contact = event.params.data;
- // contact.suggestions ...
- // contact.organization_id ...
- });
- // Data I was returning
- [
- {
- "id":36167, // ID USED IN SELECT2
- "avatar":null,
- "organization_id":28037,
- "text":"John Cena - WWE", // TEXT SHOWN IN SELECT2
- "suggestions":[
- {
- "id":28037,
- "text":"WWE",
- "avatar":null
- },
- {
- "id":21509,
- "text":"Kurt Angle",
- "avatar":null
- },
- {
- "id":126,
- "text":"Mark Calaway",
- "avatar":null
- },
- {
- "id":129,
- "text":"Ricky Steamboat",
- "avatar":null
- },
- {
- "id":131,
- "text":"Brock Lesnar",
- "avatar":null
- }
- ]
- }
- ]
Add Comment
Please, Sign In to add comment