user2240058
user2240058

Reputation:

How can I search from two fields in a select2 dropdown

I have just started using select2 and it is working fine when I fill the selections up with two fields using:

    function formatemp(item) { return  item.empnum + " : " + item.empname; }

$("#empsDropDown").select2({
     data:{ results: <?PHP echo json_encode($employees);?>, text: 'empname'},
     placeholder: " <?PHP echo lang("All");?> ",
     minimumInputLength: 2,
     allowClear: true,
     id: function(obj) {return obj.empnum;  },
     formatResult: formatemp,
     formatSelection: formatemp
 });

It displays in the format

001 : Bloggs

The search works using the

text: 'empname'

bit. so it only searches on the name. If you type 'B' in the search box, it will filter and find Bloggs etc. However if you type '0' in the search box it will return no results.

Is there anyway to get it to search both fields (empname and empnum)?

I am new to select2 so I'm hoping this is something obvious that I havent tried yet.

I have tried text: 'empname' + 'empnum' and text: 'empname', text: 'empnum'

amongst other things and I have searched the docs and on this site but I can only seem to get it to search on either one or the other, not both. I have also tried a custom matcher but that didn't seem to fit the purpose either.

Upvotes: 0

Views: 2216

Answers (1)

user2240058
user2240058

Reputation:

Found a solution by brute force. I am open to hearing any better solutions if anyone has any.

 function formatemp(item) { return  item.empnum + " : " + item.empname; }

    $("#empsDropDown").select2({
         data:{ results: <?PHP echo json_encode($employees);?>, text: formatemp},
         placeholder: " <?PHP echo lang("All");?> ",
         minimumInputLength: 2,
         allowClear: true,
         id: function(obj) {return obj.empnum;  },
         formatResult: formatemp,
         formatSelection: formatemp
     });

I just replaced text: 'empname' with text: formatemp the formatter function that I was using to populate the list with. I never expected it to work but it did, really well.

Upvotes: 1

Related Questions