I want to auto bind events of element(s) if i append element into DOM
and the element is clone object. Here is code snippet:
HTML:
<input type="button" class="clickme" value="Click Me" />
Javascript:
$(document).ready(function(){
$(".clickme").click(function(){
alert("Clicked");
var cloneElem = $(this).clone();
//cloneElem.bind("click");
cloneElem.attr("value", "Click Me" + $("input").length.toString());
$(this).parent().append(cloneElem);
});
});
Result:
If I click on Click Me1
then it should also trigger a event which is similar to Click Me
Note:
I don't want to use Live function
of JQuery to trigger event.
I want to auto bind events of element(s) if i append element into DOM
and the element is clone object. Here is code snippet:
HTML:
<input type="button" class="clickme" value="Click Me" />
Javascript:
$(document).ready(function(){
$(".clickme").click(function(){
alert("Clicked");
var cloneElem = $(this).clone();
//cloneElem.bind("click");
cloneElem.attr("value", "Click Me" + $("input").length.toString());
$(this).parent().append(cloneElem);
});
});
Result:
If I click on Click Me1
then it should also trigger a event which is similar to Click Me
Note:
I don't want to use Live function
of JQuery to trigger event.
4 Answers
Reset to default 9.clone
takes an argument whether or not to clone events as well:
$(this).clone(true);
$(document).ready(function(){
function do_logic() {
alert("Clicked");
var cloneElem = $(this).clone();
cloneElem.click(do_logic);
cloneElem.attr("value", "Click Me" + $("input").length.toString());
$(this).parent().append(cloneElem);
}
$(".clickme").click(do_logic);
});
If you don't want every handler to be cloned, this example should work.
$(document).ready(function(){
$(".clickme").click(function(){
alert("Clicked");
var cloneElem = $(this).clone();
cloneElem.click(function(){
// code to be executed when you click cloned element.
})
//cloneElem.bind("click");
cloneElem.attr("value", "Click Me" + $("input").length.toString());
$(this).parent().append(cloneElem);
});
});
you have to add click event to cloned element also.
one way to do this ..
$(".clickme").click(AddClone());
function AddClone() {
alert("Clicked");
var cloneElem = $(this).clone().click(AddClone());
//cloneElem.bind("click");
cloneElem.attr("value", "Click Me" + $("input").length.toString());
$(this).parent().append(cloneElem);
}