I know you've got your answer already, but I thought it might be worth pointing out a few things.
When creating DOM elements, you might consider using the object literal syntax, where you create the element as usual, then add its properties using key/value pairs:
$('<div'>, { class: 'myDiv'});
Ids cannot start with a number. It might be worth appending the option's value to a prefix instead:
id: "opt-" + this.value,
It's a good idea to give your new span a specific class , then alter its appearance by targeting it from a separate style-sheet. This will remove the need for all that ugly and hard to maintain, inline CSS.
These changes would give you something like:
span {
border-radius:5px;
color:#fff;
background-color:#005e3a;
padding:5px;
cursor:pointer;
width:auto;
}
<select multiple="multiple" id="mySelect">
<option value="First">First</option>
<option value="Second">Second</option>
<option value="Third">Third</option>
</select>
<div id="result"></div>
$("#mySelect").click(function () {
var span = $("<span />", {
id: "opt-" + this.value.toLowerCase(),
class: "city",
text: this.value,
click: function () {
$(this).remove();
}
});
$('#result').html(span);
});
Here's a fiddle
EDIT:
Here's how you'd do it with two elements:
$("#mySelect").click(function () {
var span1 = $("<span />", {
class: "opt-" + this.value.toLowerCase(),
text: this.value,
click: function () {
$(this).remove();
}
}),
span2 = span.clone(true);
$('#result').empty().append(span1).append(span2);
});
You have to clone the original span, as append actually moves the element, so appending it twice wouldn't work.
I also changed the id
attribute to class
, as ids should be unique to a page.