Reputation: 4116
I have some json that I am trying to use to generate a select box
The json has some elements in it that use
to provide some spacing, for example.
[
{"value":1, "text":"1"}
{"value":2, "text":" 1. a."}
{"value":3, "text":" 1. a. i."}
]
Then from my jQuery, I get those values and replace the options using .append().
$.each(response, function(id, ob) {
// Add json results
options.append($('<option>', {
value: ob.value,
text: ob.text
}));
// Apply
$('#select_list').html(options.html());
});
However, when it shows up in the HTML, it is showing the
instead of rendering an actual space.
I can modify either the jQuery or the json data, whichever one will allow me to add whitespace where required, but I am not sure how.
Upvotes: 0
Views: 1315
Reputation: 206565
Beside
being a HTML representation - therefore you need a .html()
instead of .text()
(as already noted), here are some other ways to achieve the appending
var response = [
{"value":1, "text":"1"},
{"value":2, "text":" 1. a."},
{"value":3, "text":" 1. a. i."}
];
$.each(response, function(id, ob) {
$('<option/>', {
value: ob.value,
html: ob.text,
appendTo: '#select_list'
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="select_list"></select>
var response = [
{"value":1, "text":"1"},
{"value":2, "text":" 1. a."},
{"value":3, "text":" 1. a. i."}
];
$("#select_list").append(
response.map(function(o) {
return `<option value='${o.value}'>${o.text}</option>`;
})
);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="select_list"></select>
Upvotes: 0
Reputation: 1
Try this
{"value":3, "text":encodeURIComponent(" 1. a. i.")}
Upvotes: 0
Reputation: 21505
You're wanting to insert html, not text:
$('select').append($('<option>', {
value: "foo",
text: " text" // literal text
}));
$('select').append($('<option>', {
value: "bar",
html: " html" // parsed html. (Sanitize it!)
}));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select>
</select>
Upvotes: 6