Click on 1, 2, 3 in the snippet below. How can I reach originalEvent
so the alert open up on the already selected item, the same way as the other options in the list?
I've tried the built in events, but I can't seem to find one that triggers on any select in the list, already selected or not.
$(".form-control").select2({
templateResult: formatSelect2,
});
$(".form-control").on('select2:select', function (evt) {
var origEvent = evt.params.originalEvent;
if($(origEvent.target).closest('.statuses span').length) {
var data = $(origEvent.target).parents('li[aria-selected]').data('data').text || null;
alert('Clicked \"' + $(origEvent.target).html() + '\" from the value: ' + data);
}
});
function formatSelect2 (data) {
if (!data.id) { return data.text; }
var $data = $(
'<span data-status="' + data.element.getAttribute("data-status") + '">' + data.text + '<span class="statuses"><span data-status="1">1</span><span data-status="2">2</span><span data-status="3">3</span></span></span>'
);
return $data;
}
.statuses {
margin-left: 8px;
}
.statuses span {
margin-left: 8px;
cursor: pointer;
}
.statuses span:hover {
margin-left: 8px;
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.5/css/select2.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.5/js/select2.js"></script>
<select class="form-control render_select2" style="width: 300px">
<option selected="selected" data-status="1">orange</option>
<option>white</option>
<option>purple</option>
</select>
<select class="form-control render_select2" style="width: 300px">
<option selected="selected" data-status="1">orange1</option>
<option>white1</option>
<option>purple1</option>
</select>