Setting value programatically to an AJAX Select2
See original GitHub issueI have a Select2 with AJAX that is working perfect, but for the fact that I cannot set a value using javascript. I do not refer to an initial value. The Select2 is shown initially without a value and this is expected. The control also loads the data from AJAX correctly and the user can select one of the options.
The problem is that the user can interact with the page in different ways, of which one gives me information to place in Select2; thus, I need to select a value into this Select2 that is usually loaded with AJAX.
I tried this
$("#list").select2('data',{id:"itemid",text:"item text"});
But this gives me an error “Function expected” in IE and “oject is not a function” in FireFox.
The error seems to be found in select2.full.min.js, instruction return d[b](e)
.
I also tried the “val” function, but I know that only works when selecting an item by its ID, rather than add a new selected item.
Issue Analytics
- State:
- Created 9 years ago
- Reactions:1
- Comments:18 (3 by maintainers)
As a workaround, I manipulated the SELECT directly.
$("#list").empty().append('<option value="id">text</option>').val('id').trigger('change');
Select2 follows suit accepting the new item as the selected one and showing it to the user.Would be this the recommendation or is something else supposed to be the correct answer?
@phissionmailed, thank you so much for that. I’ve been fighting this issue for weeks and every bit of discussion I could find on this had me trying to use something along the lines of $(‘element’).select2(‘data’);
My issue was similar to yours, except I’m working with an ajax tagged multiple select which may or may not contain contain initial values.
Here is what I came up with (this is part of an ajax submit function):