I wanted to give my solution which will hopefully help others.
Using Select2 v4 tableish styling and multicolumn search.
This uses local JSON data.
Quick overview of how this works:
There are 2 functions. The matcher
function and the formatSelect
.
The matcher
function is used for the query. It will check each word of the query to see if there is a match in any of the rows. Currently set to return any row that matches atleaast 1 word.
The formatSelect
function is then run once the matcher
has returned all matching rows (all rows if no query). formatSelect
adds header columns on the first row of data if its the first row being rendered.
The table in this case uses bootstrap column widths for structure.
The code:
var firstEmptySelect = true;
function formatSelect(result) {
if (!result.id) {
if (firstEmptySelect) {
console.log('showing row');
firstEmptySelect = false;
return '<div class="row">' +
'<div class="col-xs-3"><b>Client</b></div>' +
'<div class="col-xs-3"><b>Account</b></div>' +
'<div class="col-xs-3"><b>Deal</b></div>' +
'</div>';
} else {
console.log('skipping row');
return false;
}
console.log('result');
console.log(result);
}
return '<div class="row">' +
'<div class="col-xs-3">' + result.client_name + '</div>' +
'<div class="col-xs-3">' + result.account_name + '</div>' +
'<div class="col-xs-3">' + result.deal_name + '</div>' +
'</div>';
}
function matcher(query, option) {
firstEmptySelect = true;
if (!query.term) {
return option;
}
var has = true;
var words = query.term.toUpperCase().split(" ");
for (var i =0; i < words.length; i++){
var word = words[i];
has = has && (option.text.toUpperCase().indexOf(word) >= 0);
}
if (has) return option;
return false;
}
$('#selectAccountDeal').select2({
data: {!! $deals !!},
width: '100%',
templateResult: formatSelect,
templateSelection: formatSelect,
escapeMarkup: function(m) { return m; },
matcher: matcher
})
My example JSON data
[{
"text": "JL - o yea - Testing this deal",
"id": 4,
"client_name": "JL",
"account_name": "o yea",
"deal_name": "Testing this deal"
}, {
"text": "JL - test - fj;askld fj",
"id": 3,
"client_name": "JL",
"account_name": "test",
"deal_name": "fj;askld fj"
}]
HTML for select element
<select id="selectAccountDeal" name="account_deal_id" placeholder="Select your Deal" required>
<option></option>
</select>
Example of the select2 dropdown