问题
I am trying to setup my pre defined select options in select2 with ajax but when I am using the ajax and clicking on the select2 it removes the html options I had there before, any idea how can I make it to leave the options as they are and not remove them until I am typing some unrelevant char?
I believe it is not clear so I made fiddle with both cases so you will get better understanding
the HTML
<select id="e1" style="width:300px">
<option value="AL">Alabama</option>
<option value="Am">Amalapuram</option>
<option value="An">Anakapalli</option>
<option value="Ak">Akkayapalem</option>
<option value="WY">Wyoming</option>
</select>
<select id="e2" style="width:300px">
<option value="AL">Alabama</option>
<option value="Am">Amalapuram</option>
<option value="An">Anakapalli</option>
<option value="Ak">Akkayapalem</option>
<option value="WY">Wyoming</option>
</select>
the js
$("#e1").select2({ajax: {
url: "https://api.github.com/search/repositories",
dataType: 'json',
delay: 250,
data: function (params) {
return {
q: params.term, // search term
page: params.page
};
},
processResults: function (data, page) {
// parse the results into the format expected by Select2.
// since we are using custom formatting functions we do not need to
// alter the remote JSON data
return {
results: data.items
};
},
cache: true
}});
$("#e2").select2();
fiddle example of select2 ajax and none ajax
回答1:
In your server side script, where you are processing the search query the user sent, return the first 5 elements which should appear as default, even if the query is empty.
$query=$_REQUEST['q'];
if (!empty($query)) {
//populate the results if the user is typed something in
} else {
$results=array();
$results[0]['text']=Alabama;
$results[0]['id']="idofalabama";
// and so on, for the number of results you want to display when the user didn't input anything in the search box
}
return json_encode($results);
来源:https://stackoverflow.com/questions/31005271/select2-removes-default-options-when-using-ajax