Trying to work out how to use the select2 templating function with a dynamic select2 dropdown to also show the extra data in a JSON response
Example data
{"id":"12","value":"DASGDSA67","otherData":"Brunswick","extraData":"Heads"}
View (Javascript)
<script type="text/javascript">
$(document).ready(function() {
$(".company2").select2();
$(".location2").select2({
templateResult: formatState
});
});
$(".company2").select2().on('change', function() {
var $company2 = $('.company2');
$.ajax({
url:"../api/locations/" + $company2.val(),
type:'GET',
success:function(data) {
var $location2 = $(".location2");
$location2.empty();
$.each(data, function(value, key) {
$location2.append($("<option></option>").attr("value", value).text(key));
});
$location2.select2();
}
});
}).trigger('change');
function formatState (state) {
if (!state.id) { return state.text; }
var $state = $(
'<h1>' + state.element.value() + '</h1>' + '<p>' + state.element.otherData() + '</p>'
);
return $state;
};
</script>
via Chebli Mohamed
Aucun commentaire:
Enregistrer un commentaire