I'm working on removing ajax calls from select2. I have a static list of objects populating the dropdown. The workflow I'm looking at is...
At this point, I want to prepopulate the search term with what the user initially searched for, so that the user can just click the box and have it prepopulated with the results list that they selected from to get to this page. However I do not want to tamper with the available options in the static list.
I.E.
User types in "ABC", and they have a list of "ABC Company" "ABC Person" and "ABC Entity" show up to choose from.
User chooses "ABC Person" so they're taken to the ABC Person page.
User sees that this is not the page they were looking for.
User clicks the search box again, and the select2 box has "ABC" in the search term area and a list of "ABC Company" "ABC Person" and "ABC Entity" automatically displayed (as if they just searched for "ABC").
User can backspace and type in "XYZ" and a new list of "XYZ Company" "XYZ Person" "XYZ Entity" shows up without making any ajax calls.
Currently I can programmatically set the search term value, but I cannot figure out how to trigger the change event on the .select2-input box to get the results to open up and load.
Inorder to populate the select box and trigger we need this:
<select id="e1" style="width:300px;">
<optgroup label="A1 comps">
<option value="A1">AAA 1</option>
<option value="A2">AAA 2</option>
<option value="A#">AAA 3</option>
<option value="A4">AAA 4</option>
</optgroup>
<optgroup label="B1 comps">
<option value="B1">BBB 1</option>
<option value="B2">BBB 2</option>
<option value="B3">BBB 3</option>
<option value="B4">BBB 4</option>
</optgroup>
</select>
<script>
$(document).ready(function() {
$("#e1").val("B1").select2();
$("#e1").on("select2-opening", function() {
$("#e1").on("select2-open", function() {
$("#e1").select2("search","BBB");
});
});
});
</script>
But in my code we need to set the value of option (in eg: "B1") and not the searched term (eg :"ABC")
http://jsfiddle.net/abhiklpm/98mhzv5b/
Got it: :) Updated fiddle: http://jsfiddle.net/abhiklpm/98mhzv5b/1/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With