Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.clone() method in jquery without copying value [duplicate]

Tags:

html

jquery

Possible Duplicate:
Jquery clone of a textbox without the content

I use .clone in jQuery. When I clone ul it is cloning its value also. I only want to copy structure not value. When you type some value in input field and then click clone it will clone input value too.

Here is my code snippet:

<div class="str">
    <ul><li><input type="text" /></li></ul>
</div>
<a href="#">clone</a>

$(function() {
    $('a').live('click', function() {
        var cln = $('ul:last').clone();
        $('.str').append(cln);
    });
});
like image 988
Jitender Avatar asked Aug 20 '12 10:08

Jitender


People also ask

Do events also get copied when you clone an element in jQuery?

Normally, any event handlers bound to the original element are not copied to the clone. The optional withDataAndEvents parameter allows us to change this behavior, and to instead make copies of all of the event handlers as well, bound to the new copy of the element. As of jQuery 1.4, all element data (attached by the .

What is Clone function in jQuery?

The clone() is an inbuilt method in jQuery which is used to make a copy of selected elements including its child nodes, text and attributes. Syntax: $(selector).clone(true|false) Parameter: It accepts an optional parameter which could be either true or false specifies that event handler should be copied or not.

How do you clone an object in jQuery?

To clone an element using jQuery, use the jQuery. clone() method. The clone() method clones matched DOM Elements and select the clones. This is useful for moving copies of the elements to another location in the DOM.


2 Answers

You can try the code below. By the way, if you use the last version of jQuery I'd suggest using on method instead of live (here instead of body you can use any parent of a element).

$("body").on("click", "a", function() {
    $("ul:last").clone().appendTo(".str").find("input[type='text']").val("");
});​

DEMO: http://jsfiddle.net/vhq5p/18/

like image 102
VisioN Avatar answered Oct 06 '22 02:10

VisioN


Do you mean:

var cln= $("ul:last").clone().find("input").val("").end();

Demo: jsFiddle

like image 35
Sudhir Bastakoti Avatar answered Oct 06 '22 02:10

Sudhir Bastakoti