Arvin
Arvin

Reputation: 1014

HTML select control containing HTML and JavaScript tags as text

I have a select control getting values dynamically. In the script, I need to insert the following text inside the select tags as its inner html.

<option value=""></option>
<option><h1>zoot</h1></option>
<option><div>divTest</div></option>
<option><span> style="color:red;font-weight:bold;">SpanTest</span></option>
<option><option>option</optipon></option>

What I am trying to do is in the picture below enter image description here

I tried using HTMLEncode and that was not working too. Am I able to do this using JavaScript or jQuery or by any other means in html select control ?

Upvotes: 2

Views: 240

Answers (2)

H77
H77

Reputation: 5967

You can add the items to the select using jQuery and the text function.

e.g.

var vals = ["<h1>zoot</h1>",
  "<div>divTest</div>",
  "<span> style='color:red;font-weight:bold;'>SpanTest</span>",
  "",
  "option"
];

var $stuff = $("#stuff");

vals.forEach(function(val) {
  $("<option/>").text(val).appendTo($stuff);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<select id="stuff">
  <option value=""></option>
</select>

Upvotes: 1

Fenton
Fenton

Reputation: 250922

It you want the HTML to be user-visible, you need to encode it. Working example below.

<select name="example">
  <option value=""></option>
  <option>&lt;h1&gt;zoot&lt;/h1&gt;</option>
  <option>&lt;div&gt;divTest&lt;/div&gt;</option>
  <option>&lt;span&gt; style="color:red;font-weight:bold;">SpanTest&lt;/span&gt;</option>
  <option>&lt;option&gt;option&lt;/optipon&gt;</option>
 </select>

If you are trying to show previews using those HTML blocks, you may wish to drop out of select lists and provide a different user interface to do so - such as previews combined with radio inputs.

Upvotes: 0

Related Questions