Joshua
Joshua

Reputation: 9

Highlight color on specific text in selection text option

Anyone idea how do I put a color highlight containing the word "stock" (check the image).

CSS, JavaScript, jQuery, or any language will do.

screenshot.png

Upvotes: 0

Views: 298

Answers (3)

Tansukh Rathod
Tansukh Rathod

Reputation: 90

If you are using select2 then you can do it like below. You can highlight search text

CSS

<style>
.select2-rendered__match {
    background-color: greenyellow;
}
</style>

JS

<script>
    function markMatch(text, term) {
        var regEx = new RegExp("(" + term + ")(?!([^<]+)?>)", "gi");
        var output = text.replace(regEx, "<span class='select2-rendered__match'>$1</span>");
        return output;
    }

    var query = {};
    $('.js-data-example-ajax').select2({
        allowClear: true,
        minimumInputLength: 2,
        escapeMarkup: function(markup) {
            return markup;
        },
        language: {
            searching: function(params) {
                // Intercept the query as it is happening
                query = params;
                // Change this to be appropriate for your application
                return 'Searching…';
            }
        },
        templateResult: function(item) {
            if (item.loading) {
                return item.text;
                term = query.term || '';
                return markMatch(item.text, term);
            },
        }
    });
</script>

Upvotes: 0

4b0
4b0

Reputation: 22323

You can use RegExp to find the desire word and wrap your word with a span tag using replaceWith.Apply class on span tag to give desire color.

var ChangeColor = 'Stocks';
var rgx = new RegExp('\\b(' + ChangeColor + ')\\b', 'ig');

$('div').contents().each(function() {
  $(this).replaceWith($(this).text().replace(rgx, '<span class="red">$1</span>'));
});
.red {
  color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
  Some text(Stocks)
</div>
<div>
  Some text( Stocks 1)

</div>

Upvotes: 0

Augustin
Augustin

Reputation: 61

try this

<select>
  <option>ARMAGEL HT 5MM ROLL(S) BLANKET TYPE(<span>STOCKS</span>:5 from)</option>
  <option>ARMAGEL HT 5MM ROLL(S) BLANKET TYPE(<span>STOCKS</span>:5 from)</option>
  <option>ARMAGEL HT 5MM ROLL(S) BLANKET TYPE(<span>STOCKS</span>:5 from)</option>
</select>

and css style with

select option span{
  color: #ff0000;
}

Upvotes: 1

Related Questions