Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select2 Programmatically set search terms and open dropdown with relevant results (no ajax calls)

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...

  1. User clicks the select2
  2. User types into the search box (and results are displayed)
  3. User makes a selection and a new webpage loads.

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.

  1. User types in "ABC", and they have a list of "ABC Company" "ABC Person" and "ABC Entity" show up to choose from.

  2. User chooses "ABC Person" so they're taken to the ABC Person page.

  3. User sees that this is not the page they were looking for.

  4. 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.

like image 395
Bardicer Avatar asked Dec 25 '22 00:12

Bardicer


1 Answers

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/

like image 65
abhiklpm Avatar answered Dec 28 '22 12:12

abhiklpm