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();
});


functiongetOptId(text) {
  let id = '';
  $('#test_id').find('*').filter(function() {
    if ($(this).text() === text) {
      id = $(this).val();
    }
  });
  return id;
}
<linkhref="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css"rel="stylesheet" /><scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script><div><selectid="test_id"><option></option><optionvalue="1">Option 1</option><optionvalue="2">Option 2</option><optionvalue="3">Option 3</option><optionvalue="4">Option 4 TEST</option><optionvalue="5">Option 4 This is 5</option><optionvalue="6">Option 4</option></select></div><br><buttonid="text_btn">Select Option 4</button>

Post a Comment for "Setting Text Value In Select2"