High brightness typed character is not displayed in select2 selectlist

I'm trying to migrate from select2 version 2 to version 4. Typed character highlighting in the clause list was working correctly in the old version; but now it doesn't. This was the code I used to highlight:

.select2-result-selectable .select2-match, .select2-result-unselectable     .select2-match
{
text-decoration: none;
font-weight: bold;
}

      

+3


source to share


1 answer


in version 4+ you need to process templateResult. Basically, you need to get that term and replace the result with your own template.

I made a sample for you that replaces the result with another one using the one in bold. However, you can customize the result (with colors, etc.) as needed. PS: The term is filled with jquery, but you can replace it for javascript if you need.

JavaScript:

$(document).ready(function() {
  $('.selectStates').select2({
    templateResult: formatSingleResult
  });
});

function formatSingleResult(result) {
    var term =$(".selectStates").data("select2").dropdown.$search.val();
    var reg = new RegExp(term, 'gi');
    var optionText = result.text;
    var boldTermText = optionText.replace(reg, function(optionText) {return `<b>${optionText}</b>`});
    var $item = $(`<span> ${boldTermText}  </span>`);
    return $item;
}

      



HTML:

<select class="selectStates">
    <option value="AK">Alaska</option>
    <option value="HI">Hawaii</option>
    <option value="CA">California</option>
    <option value="NV">Nevada</option>
    <option value="OR">Oregon</option>
    <option value="WA">Washington</option>
    <option value="AZ">Arizona</option>
</select>

      

Here's a working example: https://codepen.io/cassioseffrin/pen/pLYyVv

0


source







All Articles