Skip to content Skip to sidebar Skip to footer

Setting Text Value In Select2

I am using Select2 (via CDN / latest version) with data loaded from an array. (Note that data is pulled via AJAX/JSON, but due to some unusual circumstances, this is loaded via an

Solution 1:

A simple example, if your option text is unique and using this could return the id for you:

$("#test_id option:contains('Option 4')").val()

then call

$('#test_id').val($("#test_id option:contains('Option 4')").val()).change();

to select it by text and call trigger change so it is selected.

To get the exact match just add a function getOptId to get the id if text provided.

// Grade
$('#test_id').select2({
  width: '200px',
  data: [],
});



$('#text_btn').click(function() {
  $('#test_id').val(getOptId('Option 4')).change();
});


function getOptId(text) {
  let id = '';
  $('#test_id').find('*').filter(function() {
    if ($(this).text() === text) {
      id = $(this).val();
    }
  });
  return id;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script>

<div>
  <select id="test_id">
        <option></option>
        <option value="1">Option 1</option>
        <option value="2">Option 2</option>
        <option value="3">Option 3</option>
        <option value="4">Option 4 TEST</option>
        <option value="5">Option 4 This is 5</option>
        <option value="6">Option 4</option>
    </select>
</div>
<br>
<button id="text_btn">Select Option 4</button>

Post a Comment for "Setting Text Value In Select2"