Reputation: 5030
Let say I have this select box:
<select id="example" multiple="multiple" style="width: 300px">
<option selected value="1">January</option>
<option value="2">February</option>
<option value="3">March</option>
<option value="4">April</option>
<option value="5">May</option>
<option value="6">June</option>
<option value="7">July</option>
<option value="8">August</option>
<option value="9">September</option>
<option value="10">October</option>
<option value="11">November</option>
<option value="12">December</option>
</select>
For communicating with many other parts of the site, the value cannot be changed. This is just for demo example, the actual use case is something more complicated and the display value need to be different with the actual form value that is going to be submitted.
To allow autocomplete and adding new tag, select2 is used.
$('#example').select2({
placeholder: 'Select a month',
tags: true,
tokenSeparators: [',', ' ']
});
The problem is that when typing the full month name, like "January", and then press space, instead of selecting the existing "January" option (which is what I expected), it just creates a new tag with value January
.
After some repeated testing, I found that this just happens when the actual value is not the same as the display value. Is there a way I can keep the two values different but make it select the already exist option?
Upvotes: 0
Views: 1242
Reputation: 16540
Utilise the createTag
event by searching for a match.
If there's no match, and since you don't want to add a new tag, simply return null
:
var options = $('#example option');
$('#example').select2({
placeholder: 'Select a month',
tags: true,
tokenSeparators: [',', ' '],
createTag: function(params) {
var matchedVal = options.filter(function () { return $(this).html() === params.term; }).val();
return (matchedVal) ? { id: matchedVal, text: params.term } : null
}
});
Demo: https://jsfiddle.net/2yu87gyf/
EDIT:
Per your comment that you want to create the tag if it doesn't already exist - use this return
statement instead:
return (matchedVal) ? { id: matchedVal, text: params.term } : { id: params.term, text: params.term }
Create unmatched tag demo: https://jsfiddle.net/2yu87gyf/1/
Upvotes: 2
Reputation: 2675
Try this
remove tags option as it will create new tags on the fly
$('#example').select2({
placeholder: 'Select a month',
tokenSeparators: [',', ' ']
});
Upvotes: 0