Select2 w/ ajax multiselect
HTML
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<p>
Hidden field value set in the following format:
<br />
<em>
'34:Donnie Darko,54:Heat,27:No Country for Old Men'
</em></p>
<input type='hidden' id="e6" style="width: 500px;" value="34:Donnie Darko,54:Heat,27:No Country for Old Men" />
<br />
<button id="save">Save</button>
<p>
After it's initialised, the hidden field value will change to:<br />
<em>
'34,54,27'
</em>
<br />
That is the value sent to the server
</p>
JavaScript
$("#e6").select2({
placeholder: "Search for a movie",
minimumInputLength: 1,
ajax: { // instead of writing the function to execute the request we use Select2's convenient helper
url: "http://api.rottentomatoes.com/api/public/v1.0/movies.json",
dataType: 'jsonp',
data: function (term, page) {
return {
q: term, // search term
page_limit: 10,
apikey: "ju6z9mjyajq2djue3gbvv26t" // please do not use so this example keeps working
};
},
results: 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 remote JSON data
return {results: data.movies};
}
},
function formatResult(movie) {
return '<div>' + movie.title + '</div>';
};
function formatSelection(data) {
return data.title;
};
$('#save').click(function() {
alert($('#e6').val());
});