1

I'm trying to find the value of a textarea that exists inside a cloned element, and then change that value, but I keep getting 'undefined' values when I write them out to the console.

my template:

<script type="text/template" data-template="test">
    <div id="content">
        <textarea id="txta">123</textarea>
    </div>
</script>

my js code:

$("#btnChange").on('click', function() {
    var templateName = 'test';
    var html;
    var el;
    el = $("script[data-template=" + templateName + "]");
    html = el.html();
    console.log('html: ' + html);                     //**this works**

    var clone = $(el).clone();
    console.log("clone: " + clone.html());            //**this works**

    var textarea = $(clone).find("textarea");
    console.log("txt val: " + textarea.val());        //**undefined**

    textarea.val("abc");
    console.log("txt val: " + textarea.val());
});
4

1 回答 1

2

clone is the script tag which contains text. Therefore, it doesn't contain a textarea for you to manipulate. you have to convert the text into a dom fragment.

var textarea = $(clone.html()).find("textarea");

Demo: http://jsfiddle.net/Tentonaxe/wtUBQ/

Note, that doesn't actually change clone in any way.

I'd suggest doing it this way:

$("#btnChange").on('click', function () {
    var templateName = 'test';
    var html;
    var el;
    el = $("script[data-template=" + templateName + "]");
    html = el.html();
    console.log('html: ' + html); //**this works**

    var template = $.parseHTML($(el).text());
    console.log("template: " + template); //**this works**
    var textarea = $(template).find("textarea");
    console.log("txt val: " + textarea.val()); //**undefined**

    textarea.val("abc");
    console.log("txt val: " + textarea.val());
    $("body").append(template);
});

http://jsfiddle.net/Tentonaxe/wtUBQ/1/

于 2013-10-31T19:59:20.243 回答