Reputation: 9407
I implemented a select2
dropdown that allows the user to enter a custom input...
$("#select").select2({
createSearchChoice:function(term, data) {
if ($(data).filter(function() {
return this.text.localeCompare(term)===0;
}).length===0)
{return {id:term, text:term};}
},
multiple: false,
selectOnBlur: true,
data: [{id: 1, text: '1'}, {id: 2, text: '2'}, {id: 3, text: '3'}]
});
This works fine, but there is a scenario where I need to programatically set a custom value for the select2
dropdown. I tried doing the following...
// Doesn't work
$('#select').val('val', custom);
// Doesn't work
$('#select').val(custom);
Is there any way to do this?
Working fiddle of my select dropdown.
Upvotes: 0
Views: 2132
Reputation: 9407
I found out how to accomplish what I want. The solution was...
$('#select').select2('data', {id: id, text: custom});
The following will set the input as whatever value custom
is without adding to the list itself.
Here is a working fiddle.
Upvotes: 1
Reputation: 490
Do you want to show selected value? if so you can add
$('#select').val(custom).attr("selected", "selected").change();
Upvotes: 0
Reputation:
If I remember correctly, you need to trigger the change for select2 to take effect.
$('#select').val(custom).change();
Upvotes: 0