0

I have an array of hashes each comprised of string based key/value pairs. Strangely though I noticed that when the loop complete and if there's an apostrophe within the string, any characters after the apostrophe are omitted (including the apostrophe). For instance if I had a name value Randy's Donuts it would show only as Randy in the input. Is there way I can dynamically escape these apostrophes (let alone any other special characters that I don't know about) within the the loop?

$(function() {
  var brands = [{name: "Randy's Donuts"}, {name: "Joe's American Bar & Grill"}, {name: "Macy's"}];

  for (var i = 0; i < brands.length; i++) {
    var brandName   = "<td><input type='text' value='" + brands[i]["name"] + "'></td>";
    var $tr         = "<tr>" + brandName + "</tr>";
    
    $("table").append($tr);
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="">
   <table></table><br />
   <input type="submit" />
</form>
Carl Edwards
  • 13,826
  • 11
  • 57
  • 119

1 Answers1

1

The issue is because you need to either escape the ' in the brands which are appended to the string, or change the string delimiters to ' and use " to delimit the attribute values. The latter is much more straight-forward. Try this:

$(function() {
    var brands = [{ name: "Randy's Donuts" }, { name: "Joe's American Bar & Grill" }, { name: "Macy's" }];
    for (var i = 0; i < brands.length; i++) {
        var brandName = '<td><input type="text" value="' + brands[i]["name"] + '"></td>';
        var $tr = "<tr>" + brandName + "</tr>";
        $("table").append($tr);
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="">
    <table></table>
    <br />
    <input type="submit" />
</form>
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339