0

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>
SeaBass
  • 1,584
  • 4
  • 20
  • 46
  • 1
    Doesn't seem like every event from the list exposes the same origEvent. I referred to [this](https://stackoverflow.com/questions/15636302/attach-click-event-to-element-in-select2-result) ( a better option) as well but it is similar to what I had in the previous post as first answer i.e. getting the instance and assigning the event. So it'd be okay to use an `each` loop I suppose. Also, for keyboard events, use `if else` to check for `origEvent`. – Shashank Aug 23 '18 at 21:57
  • Interesting! Thank you so much. Guess what, `mouseup` is not blocked by select2 so I can just use that! Easy! :) – SeaBass Aug 23 '18 at 22:12
  • True. `mouseup` works! Anyway, glad we could work it out. Happy coding! – Shashank Aug 24 '18 at 04:26
  • 1
    Thank you kindly! – SeaBass Aug 24 '18 at 04:46

0 Answers0