jQuery .html() does not copy contents of textareas

2019-05-03 12:23发布

I'm trying to copy the contents of an element using elem.html() but it's not including the contents of inputs or textareas.

Here's an example (try writting in the boxes then click "Copy"): http://jsfiddle.net/gAMmr/2/

Is there a way of copying all info?

These are the approaches I have tried so far:

  • elem.clone() - not suitable for my task because it copies the element itself
  • elem.children().clone() - misses out text nodes
  • elem.contents().clone() - doesn't include the textarea contents

EDIT: The results seem to be different in each browser. I'm using Chrome.

4条回答
ら.Afraid
2楼-- · 2019-05-03 12:48

Inputs don't contain HTML, they have values. Use .val() for form elements.

查看更多
做个烂人
3楼-- · 2019-05-03 12:56

How about checking the type of the element you're trying to grab the inner text from and if it's an input or textarea use $.text() instead of $.html()

查看更多
兄弟一词,经得起流年.
4楼-- · 2019-05-03 12:58

As Šime Vidas pointed out earlier, this is a 4-year old bug which hasn't been corrected, though a fix exists which is quite simple to apply:

-Download jquery.fix.clone.js
-Include it in your page: <script src='path/to/jquery.fix.clone.js'></script>

From then on cloned textarea elements should include the text of their source (note: you need to use the .clone() method to create your new textarea, not .html()).

查看更多
你好瞎i
5楼-- · 2019-05-03 13:06
$("button").click(function () {
    $("#2").html($("#1").html());
    $("#1").find("input").each(function(idx) {
        $("#2").find("input").eq(idx).val($(this).val());
    });
    $("#1").find("textarea").each(function(idx) {
        $("#2").find("textarea").eq(idx).val($(this).val());
    });
});

http://jsfiddle.net/gAMmr/5/

查看更多
登录 后发表回答