AJAX filled Select2 not clickable

I am using Select2 for the project. The second selection box is populated depending on the selected item in the first field, as shown in the link below. However, for some reason, I cannot click on the first item in the second selection field. The only way to select the first item if I want is to first select another user, and then return to the first. How can i solve this?

Video:

enter image description here

My code is:

This is the first selection field populated with regular PHP (Laravel). Everything is fine here.

<div class="form-group"> <label for="select"> Partner: </label> <select id="select" name="select" class="searchselect searchselectstyle"> @foreach($partners as $i => $partner) <option {{$i == 0 ? 'selected' : ''}} value="{{$partner->id}}">{{$partner->name}}</option> @endforeach </select> </div> 

Here is the second error checkbox.

 <div class="form-group" > <label for="select2"> Hoofdgebruiker: </label> <select id="select2" style="min-width: 200px;" name="select2" class="searchselect searchselectstyle"> </select> </div> <script type="text/javascript"> $(document).ready(function(){ var url = '/json/getusers'; var $post = {}; $post.id = $("select").val(); $.ajax({ type: "POST", dataType: "json", url: url, data: $post, cache: false }).done(function(data){ $('#select2') .find('option') .remove() .end(); $.each(data, function(i, value) { console.log(data); $('#select2').append($('<option>').text(value.text).attr('value', value.id)); }); } ); }); 

-

 public function getusers(){ if(!isset($_POST['term'])){ $users = User::where('partner_id', $_POST['id'])->get(); }else{ $wildcard = '%'.$_POST['term'].'%'; $users = User::where('partner_id', $_POST['id'])->where('email', 'LIKE', $wildcard)->get(); } $array = array(); foreach($users as $i => $user){ $array[$i] = array("id" => $user->id, "text" => $user->email); } return response()->json($array); } 
+5
source share
2 answers

I found a solution that looks like this:

 <script type="text/javascript"> $(document).ready(function() { $(".searchselect").select2(); search(); $("#select").change(function(){ search(); }); }); function search(){ var $post = {}; $post.id = $("#select").val(); $("#select2").select2({ ajax: { dataType: "json", type: "POST", data: function (params) { var query = { term: params.term, id: $post.id }; return query; }, url: '/json/getusers', cache: false, processResults: function (data) { return { results: data }; } } }); } </script> 

Now I use the usual AJAX functions created in Select2, now everything works as expected!

+1
source

Check the case sensitivity of the id key in json data. You are probably returning "id" insteat "id".

 {"results":[{"id":"3","text":"Exampe 3"},{"id":"4","text":"Example 4"},{"id":"16","text":"Example 16"}]} 

I do not like

 {"results":[{"id":"3","text":"Exampe 3"},{"id":"4","text":"Example 4"},{"id":"16","text":"Example 16"}]} 
0
source

Source: https://habr.com/ru/post/1243527/


All Articles