How to get jquery-select2 to display html entities correctly?
Asked Answered
B

1

7

I'm using jquery-select2 4.0.0 and I want to display a text containing an '&'.

This is the code of the option:

<option value="123">
   123 - This & That
</option>

However, Select2 shows the following as the option text:

123 - This &amp; That

How can I get Select2 to show the specialchar correctly?

Batchelder answered 10/3, 2015 at 14:35 Comment(1)
Just a heads up, this was because of a bug that we just fixed in the new version.Pippy
S
12

You can fix that with the help of escapeMarkup option.

<select id="s2">
    <option value="123">123 - This & That</option>
</select>

<script>
$(document).ready(function() {
    $('#s2').select2({
        escapeMarkup: function (text) { return text; }
    });
});
</script>

Here's the demo on jsfiddle.

You should take a look at this GitHub issue and look for escapeMarkup on the documentation.

Strong answered 10/3, 2015 at 15:0 Comment(4)
@Batchelder I'm glad my answer was useful. Please take a moment to check how to accept an answer if this answer solved your issue. Thanks!Arni
I know I am replying late on this answer, but won't this enable XSS possibility and has security vulnerability? Example if we are escaping user input as select2 option, then user can inject malacious script on it right?Haerr
try this select option: <option value="123">123 <script>alert('script');</script> - This & That</option>Haerr
github.com/select2/select2/issues/3115#issuecomment-77664168Haerr

© 2022 - 2024 — McMap. All rights reserved.