Bobby S
Bobby S

Reputation: 4116

jQuery append not working with  

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 &nbsp; 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

Answers (3)

Roko C. Buljan
Roko C. Buljan

Reputation: 206565

Beside &nbsp; 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":"&nbsp;1. a."},
  {"value":3, "text":"&nbsp;&nbsp;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":"&nbsp;1. a."},
  {"value":3, "text":"&nbsp;&nbsp;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

O.Damra
O.Damra

Reputation: 1

Try this

{"value":3, "text":encodeURIComponent("&nbsp;&nbsp;1. a. i.")}

Upvotes: 0

Daniel Beck
Daniel Beck

Reputation: 21505

You're wanting to insert html, not text:

  $('select').append($('<option>', {
    value: "foo",
    text: "&nbsp;&nbsp;&nbsp;text" // literal text
  }));


  $('select').append($('<option>', {
    value: "bar",
    html: "&nbsp;&nbsp;&nbsp;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

Related Questions