I have a textarea inside a form:
<form action="#" id="container">
<textarea id="txt" cols="100" rows="5">Good bye</textarea>
</form>
All I want is to replace this form by a div:
$("#container").replaceWith(function() {
return "<div>" + $(this).html() + "</div>";
});
That works without any problem, but if I before to use the replaceWith method change the textarea value:
$("#txt").val("hello world");
The final content is a textarea inside the div with the “Good bye” text, not the “hello world” as expected. You have a demo here.
Why is this happening? How can I replace the form by a div preserving textarea contents?
This works:
The issue come with serializing the html with
.html(). It’s much better to work in terms of DOM Nodes. This’ll also preserve event handlers.Here’s another way: