views:

22

answers:

3

Hello,

I have html

<table>
<tr><td id="cell">&lt;a href=&quot;&quot;&gt;Google.com&lt;/a&gt;</td></tr>
</table>

<div id="to"></div>

And I have javascript

$(document).ready(function() {
   var html = '<input type="text" value="'+$("#cell").html()+'" />'
   $("#to").append(html);
});

I don't know why, but when executing this code I'm getting only <a href= in input. In firebug's inspector input html appears as <input type="text" a&gt;="" &gt;google.com&lt;="" value="&lt;a href=" > As you can see, $quot; are replaced with " - this is the problem.

I've tried using .text() instead of .html() - almost the same situation.

What is my mistake?

Thank you.

+2  A: 

You need to encode the value (set via .val() in this case), not use it directly in a string, like this:

$(document).ready(function() {
   var html = $('<input type="text" />').val($("#cell").html());
   $("#to").append(html);
});

You can see it in a demo here. The problem is the &quote; gets decoded to " which is making your HTML look like this:

<input type="text" value="&lt;a href=""&gt;Google.com&lt;/a&gt;" />

You can see how that makes the browser a little crazy :)

Nick Craver
I would guess it should be `val(...text())` here rather than `html()`? Unless the user really wants to see `<` in the input value?
bobince
A: 

Try this:

$(document).ready(function() {
   $('<input type="text">').val($("#cell").html()).appendTo("#to");
});

Avoid building HTML from strings and variables, use the functions jQuery and the DOM give to you to assign values to attributes or change an element's text. It's safer this way, and IMHO it's more readable as well.

Tomalak
A: 

Try to write customize function to unescape the string

function unescape(html) {
  return html.
    replace(/&amp;/gmi, '&').
    replace(/&quot;/gmi, '"').
    replace(/&gt;/gmi, '>').
    replace(/&lt;/gmi, '<')
}
Chinmayee
That is not recommendable. HTML parsing involves a bit more than replacing a few strings, and functions like one this usually make it worse somewhere down the road.
Tomalak
bobince