Warm tip: This article is reproduced from stackoverflow.com, please click
javascript jquery jquery-select2 select

how to display select2 after user input 3 data

发布于 2020-03-28 23:16:57

I have select2 here to display user email data, but data can be up to tens of thousands, and that makes my select2 very slow, is there a method to only display after 3-letter user input?

this my script select2

$('#add_form').find("#list_user").select2({
                              width: "100%",
                              placeholder: "Choose User by Email...",
                              ajax: {
                                url: "{{ route('getuser') }}",
                                dataType: "json",
                                delay: 250,
                                processResults: function(data) {
                                  return {
                                    results: $.map(data, function(obj) {
                                      return {
                                        id: obj.email,
                                        text: obj.email
                                      };
                                    })
                                  };
                                },
                              }
                            });

and this my controller

public function getUser(Request $request)
        {
            $search = $request->input('term', '');
            $user = DB::table('users.users')->where('email','LIKE','%'.$search.'%')
                    ->get();
            return response()->json($user);
        }
Questioner
Newbie 123
Viewed
40
Zulqarnain Jalil 2020-01-31 18:47

the only solution for your problem is to take only some records and display them. and then from select you need to call the controller to search data again and display it.

for that purpose you can change the your query to

user = DB::table('users.users')->where('email','LIKE','%'.$search.'%')->take(10)->get()

for searchable select you can reference this link and this JSFiddle link