I have a select2js select
field which retrieves a list of diseases based on user query to a database. The type of select is tags so that if the entry is not in the database, the user can add their own. An example of what it looks like is seen below:
The options below are populated by an ajax call made to a local api to retrieve the diseases from a database.
How can we write: "Suggestions" below the user input or hide the user input from the dropdown (seen above as "IgA ne") so that the user is more likely directed to choose one of the options from the database?
Some sample code:
HTML
<select id="diseases" class="form-control selectmultiple" name="diseases[]" multiple="multiple" aria-describedby="diseasesHelp">
</select>
<small id="diseasesHelp" class="form-text text-muted">If known to appear in certain diseases e.g. Tn syndrome</small>
JS
$('#diseases').select2({
tags: true,
placeholder: 'Select an item',
minimumInputLength: 3,
ajax: {
url: '/diseaseSelector',
dataType: 'json',
delay: 250,
processResults: function (data) {
return {
results: $.map(data, function (item) {
return {
text: item.name,
id: item.id
}
})
};
},
}
});
About the "Suggestions" below the user input, you could use Option Group. Using Ajax, the options should be in a Option Group object, in this format:
{
"text": "Group Name",
"children": [] // your options
}
So, in your case :
processResults: function (data) {
return {
results: [{
text: "Suggestions",
children: $.map(data, function (item) {
return {
text: item.name,
id: item.id
}
})
}]
};
},