Select2 w/ ajax multiselect
by maxisam
HTML
<link rel="stylesheet" href="http://ivaynberg.github.com/select2/select2-3.1/select2.css">
<script src="http://ivaynberg.github.com/select2/select2-3.1/select2.js"></script>
<link rel="stylesheet" href=" http://ivaynberg.github.com/select2/bootstrap/css/bootstrap.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;" />
<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
function MultiAjaxAutoComplete(element, url) {
$(element).select2({
placeholder: "Search for a movie",
minimumInputLength: 1,
multiple: true,
id: function(e) { return e.id+":"+e.title; },
ajax: {
url: url,
dataType: 'jsonp',
data: function(term, page) {
return {
q: term,
page_limit: 10,
apikey: "z4vbb4bjmgsb7dy33kvux3ea" //my own apikey
};
},
results: function(data, page) {
return {
results: data.movies
};
}
},
formatResult: formatResult,
formatSelection: formatSelection,
initSelection: function(element, callback) {
var data = [{id:'34',title:'Donnie Darko'}];
//$(element).val('');
callback(data);
}
});
};
function formatResult(movie) {
return '<div>' + movie.title + '</div>';
};
function formatSelection(data) {
return data.title;
};
MultiAjaxAutoComplete('#e6', 'http://api.rottentomatoes.com/api/public/v1.0/movies.json');
$('#save').click(function() {
alert($('#e6').val());
});