Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
197
rated 0 times [  199] [ 2]  / answers: 1 / hits: 67307  / 13 Years ago, thu, october 13, 2011, 12:00:00

I'm building up a row to insert in a table using jQuery by creating a html string, i.e.



var row = ;
row += <tr>;
row += <td>Name</td>;
row += <td><input value='+data.name+'/></td>;
row += </tr>;


data.name is a string returned from an ajax call which could contain any characters. If it contains a single quote, ', it will break the HTML by defining the end of the attribute value.



How can I ensure that the string is rendered correctly in the browser?


More From » html

 Answers
18

You just need to swap any ' characters with the equivalent HTML entity character code:



data.name.replace(/'/g, &#39;);


Alternatively, you could create the whole thing using jQuery's DOM manipulation methods:



var row = $(<tr>).append(<td>Name</td><td></td>);
$(<input>, { value: data.name }).appendTo(row.children(td:eq(1)));

[#89634] Wednesday, October 12, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jacquezf

Total Points: 27
Total Questions: 109
Total Answers: 98

Location: Lesotho
Member since Wed, Jun 2, 2021
3 Years ago
;