May.D
May.D

Reputation: 1910

Why jQuery append() removes words after first blank space in string

I'm trying to dynamically generate a form after an ajax request. Below is the relevant code sample :

for (var i in response.responseJSON[0].fields) {
  var field = response.responseJSON[0].fields[i];
  $('#properties_form').append('<label for=' + i + '>' + i + '</label>' +
                    '<input id=' + i + ' value=' + field + '>');
}

My problem is that, when var i and var field are strings with blank spaces like "Hello world", my label and inputs will be like <label id="Hello" world=""> and <input value="Hello" world="">. However, the label text will be displayed correctly i.e. <label>Hello world</label>.

I've no idea what kind of sorcery that is, but I'll be very grateful for any help. Thanks in advance.

Upvotes: 2

Views: 781

Answers (2)

rrk
rrk

Reputation: 15846

Use " to enclose the attributes.

$('#properties_form')
      .append('<label for="' + i + '">' + i + '</label>' +
                '<input id="' + i + '" value="' + field + '">');

EDIT

This will break for the cases where the value for i is something like This "works". Best solution is to append as jQuery or JS objects rather than using HTML string just like Daniel's answer.

Following snippet contains the correct fix for this. Updated based on the answer from Daniel.

i = 'Hello "World"';
field = 'Hello "World"s';
$('#properties_form')
      .append($('<label>').attr('for', i).text(i))
      .append($('<input>').attr('id', i).val(field));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="properties_form"></div>

Upvotes: 4

Daniel A. White
Daniel A. White

Reputation: 190952

There's a much more robust way of doing this.

for (var i in response.responseJSON[0].fields) {
  var field = response.responseJSON[0].fields[i];
  $('#properties_form')
     .append($('<label>').attr('for', i).text(i))
     .append($('<input>').attr('id', i).val(field));
}

You won't have to worry about the content of the strings as jQuery and the DOM will handle it for you. Not to mention this is much easier to read.

Upvotes: 9

Related Questions