wertecs
wertecs

Reputation: 1021

jQuery prepend optgroup with label

I am trying to prepend an optgroup to a select element

HTML:

<select id="select"></select>

JS :

var newItemMessage = "For new item start typing";
$("#select").prepend('<optgroup label='+newItemMessage+'></optgroup>');

here is my JSFiddle https://jsfiddle.net/nx19jotb/1/

the problem is, that only the first word from the variable is added to the label, this is appended (note the quotes after the first word)

<optgroup label="For" new item start typing></optgroup>

What am I missing?

Upvotes: 0

Views: 70

Answers (2)

Chandan Rai
Chandan Rai

Reputation: 10377

this one works as well

var newItemMessage = "For new item start typing";
$("<optgroup>").attr('label', newItemMessage).prependTo("#select");

Upvotes: 1

ymz
ymz

Reputation: 6924

the original code:

var newItemMessage = "For new item start typing";
$("#select").prepend('<optgroup label='+newItemMessage+'></optgroup>');

the fix:

var newItemMessage = "For new item start typing";
$("#select").prepend('<optgroup label="'+newItemMessage+'"></optgroup>');

Upvotes: 3

Related Questions