简体   繁体   中英

How do I find the value of textarea in jQuery cloned element?

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());
});

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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM