收录日期:2021/01/22 00:52:55 时间:2010-03-31 04:10:14 标签:javascript,jquery

Please help!

I have some form elements in a div on a page:

<div id="box">
   <div id="template">
       <div>
       <label for="username">Username</label>
       <input type="text" class="username" name="username[]" value="" / >
       <label for="hostname">hostname</label>
       <input type="text" name="hostname[]" value="">
       </div>
    </div>
</div>

using jquery I would like to take a copy of #template, manipulate the values of the inputs and insert it after #template so the result would look something like:

<div id="box">
   <div id="template">
       <div>
       <label for="username">Username</label>
       <input type="text" class="username" name="username[]" value="" / >
       <label for="hostname">hostname</label>
       <input type="text" name="hostname[]" value="">
       </div>
    </div>
       <div>
       <label for="username">Username</label>
       <input type="text" class="username" name="username[]" value="paul" / >
       <label for="hostname">hostname</label>
       <input type="text" name="hostname[]" value="paul">
       </div>
</div> 

I am probably going about this the wrong way but the following test bit of javascript code run in firebug on the page does not seem to change the values of the inputs.

var cp = $('#template').clone();

cp.children().children().each( function(i,d){
    if( d.localName == 'INPUT' ){
        $(d).val('paul'); //.css('background-color', 'red');
     }
    });
$("#box").append(cp.html());

although if I uncomment "//.css('background-color', 'red');" the inputs will turn red.

I slightly modified your HTML by assigning a "hostname" class to the hostname input. Here's the updated HTML:

<div id="box">
    <div id="template">
        <div>
            <label for="username">Username</label>
            <input type="text" class="username" name="username[]" value="" / >
            <label for="hostname">hostname</label>
            <input type="text" class="hostname" name="hostname[]" value="">
         </div>
    </div>
</div>​​​

And here's a JS:

$(function() {
    $('#template div:first').clone().appendTo("#box");
    $('#box div:last .username').val("Paul");
    $('#box div:last .hostname').val("google");
});

Also, you might want to take a look the jQuery Template proposal at http://wiki.github.com/nje/jquery/jquery-templates-proposal

Why not just use a selector for input elements with the clone as root like so:

$( "input", cp ).val("paul");

instead of using the calls to children?

EDIT: It looks like as of jQuery 1.4, when you call clone, it should also copy the data of the elements instead of just the markup. That may solve your problem of having to copy over the values directly. Relevant piece of documentation (emphasis mine):

withDataAndEventsA Boolean indicating whether event handlers should be copied along with the elements. As of jQuery 1.4 element data will be copied as well.