21

I want to clone a <select> tag with it's data attribute but without its events.

Following JQuery Official .clone() api, I understand I can clone without data and events by calling $('#grolsh').clone(), or perform a

$('#grolsh').clone(true) which will copy data and events.

I want to keep the data but clear the events associates with the original item.

Gal Bracha
  • 19,004
  • 11
  • 72
  • 86

5 Answers5

21

As from version 1.7, off() is the preferred method for unbinding:

$('#grolsh').clone(true).off();
Adriano Carneiro
  • 57,693
  • 12
  • 90
  • 123
11

Just use

$('#grolsh').clone(); // Copies the element structure

$('#grolsh').clone(true) // Copies both data and events along with the structure

$('#grolsh').clone(true).off() // Copies both data and events and removes handlers

Events bound with .on() and removed using .off();

Events bound with .bind() and removed using .unbind();

Sushanth --
  • 55,259
  • 9
  • 66
  • 105
  • first case is not true, data isn't copied with `clone()` and no arguments http://jsfiddle.net/ALxz4/ – charlietfl Oct 30 '12 at 15:26
  • The docs states "As of jQuery 1.4, all element data (attached by the .data() method) is also copied to the new copy." but from my testing, normal clone() didn't copy the data – Gal Bracha Oct 30 '12 at 15:28
2

By adding an .off():

$('#grolsh').clone(true)
    .attr({'id': 'newGrolsh'})
    .off()
    .appendTo('#target');

Updated: As Adrian suggested .off would be a better solution over .unbind

Gal Bracha
  • 19,004
  • 11
  • 72
  • 86
1

As of from jQuery version 1.5, you can pass second parameter (See: .clone( [withDataAndEvents ] [, deepWithDataAndEvents ] ))not to copy the event handler:

$('#grolsh').clone(true,false);
Bhojendra Rauniyar
  • 83,432
  • 35
  • 168
  • 231
  • Nope, that is just "A Boolean indicating whether event handlers and data for all children of the cloned element should be copied. " - it may seem like it if your `#grolsh` does not have any events, just data... but it is not like that. – jave.web Apr 14 '16 at 21:20
0

If you really just want to copy data attached by the .data() method don't abuse event (un)binding and just do:

var $original = $(".originalSelector");
var $clone = $original.clone().data( $original.data() );

Because when you pass an object to .data() method, it extends the current data with it.

!IMPORTANT NOTE!
You can't do this if you are going to use something that stores DOM references and uses it e.g. jQuery UI draggable etc...
=> only use on "pure" data / basic types

jave.web
  • 13,880
  • 12
  • 91
  • 125