Reputation: 9947
I am trying to a a drop down to a dynamically created div. But it is not letting me to change the value, i think it's not getting focused.
$(document).ready(function () {
wrapper = jQuery("<div />", {
"class": "class1",
"id": "dynamic1",
"style": "background-color:beige; border:1px solid red;width:94%;",
"text": "dynamically added div"
}).appendTo($("#sample"));
$('body').on("click", "#dynamic1", function () {
$(this).html($("#changeUserform").html());
});
});
I have implemented a sample fiddle to demonstrate my problem.
Drop down will open by clicking the newly created div.
Upvotes: 1
Views: 131
Reputation: 25527
The problem is that, everytime you click on dropdown, click event of div is generated. which causes the new dropdown to be added. Try like this
$(document).ready(function () {
wrapper = jQuery("<div />", {
"class": "class1",
"id": "dynamic1",
"style": "background-color:beige; border:1px solid red;width:94%;",
"text": "dynamically added div"
}).appendTo($("#sample"));
$("#sample").append($("<input/>", {
type: "button",
value: "add",
id: "dynamic2"
}));
$('body').on("click", "#dynamic2", function () {
$("#dynamic1").html($("#changeUserform").html());
});
});
Or you should unbind the click event from that event after the first click. USe off
for that.
$(document).ready(function () {
wrapper = jQuery("<div />", {
"class": "class1",
"id": "dynamic1",
"style": "background-color:beige; border:1px solid red;width:94%;",
"text": "dynamically added div"
}).appendTo($("#sample"));
$('body').on("click", "#dynamic1", function () {
$("#dynamic1").html($("#changeUserform").html());
$('body').off("click", "#dynamic1");
});
});
Upvotes: 1
Reputation: 59232
This code is the problem:
$('body').on("click", "#dynamic1", function () {
$(this).html($("#changeUserform").html());
});
Whenever you are clicking the div, you are overwriting the existing html, which is the problem
Change the click
event to dblclick
, though now, you have to double click it.
Demo: http://jsfiddle.net/AmitJoki/X2SPM/4/
Upvotes: 1
Reputation: 1477
You can change the ON click
event and fire it only once !
$('body').one("click", "#dynamic1", function () {
I believe it should work !
Check your updated fiddle
Upvotes: 4