How to get closest id from select2 close button?

Viewed 218

I am using Select2 Multiple Selection

Clicking on x I want ID of table row.

enter image description here

This is a code snippet to see the real problem. https://jsfiddle.net/ja1omn9x/

I am using this code:

But it's giving me undefined What should be the way?

$(document).on('click', '.select2-selection__choice__remove', function(e) {
  console.log("YES: ", $(this).closest('tr').attr('id'));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<tr id="row1">
  <td data-select2-id="4">
    <select name="product_id[]" class="invoiceProducts">
      <option value="12" data-select2-id="19">Orange</option>
      <option value="14" data-select2-id="20">Apple</option>
    </select>
    <span class="select2>
      <span class=" selection ">
        <span class="select2-selection select2-selection--multiple ">
          <ul class="select2-selection__rendered ">
             <li class="select2-selection__choice " title="Apple " data-select2-id="23 ">
<span class="select2-selection__choice__remove " role="presentation ">×</span>Apple</li>
         </ul>
        </span>
       </span>
      <span class="dropdown-wrapper " aria-hidden="true ">
    </span>
  </span>
 </td>
</tr>

1 Answers

You can use select2:unselecting this will get called whenever you click on x button then you can use .closest("tr").prop("id") to get id of row.

Demo Code :

$(".js-example-basic-multiple-limit").select2({
  maximumSelectionLength: 2
});

$('.js-example-basic-multiple-limit').on('select2:unselecting', function(e) {
  console.log('I am in :)');
  console.log("YES: ", $(this).closest('tr').prop('id'));
});
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/select2@4.1.0-beta.1/dist/css/select2.min.css">
<script src="https://code.jquery.com/jquery-3.5.0.js"></script>

<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-beta.1/dist/js/select2.min.js"></script>

<table>
  <tr id="row1">
    <td>
      <select class="form-control js-example-basic-multiple-limit" multiple="multiple">
        <option selected="selected">orange</option>
        <option>white</option>
        <option selected="selected">purple</option>
      </select>
    </td>
  </tr>
  <tr id="row2">
    <td>
      <select class="form-control js-example-basic-multiple-limit" multiple="multiple">
        <option selected="selected">orange</option>
        <option>white</option>
        <option selected="selected">purple</option>
      </select>
    </td>
  </tr>
</table>

Related