Simple Dropdown appended to dynamic div not working

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.

jquery

$(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.

Demo Fiddle

Drop down will open by clicking the newly created div.

Upvotes: 1

Views: 131

Answers (3)

Anoop Joshi P
Anoop Joshi P

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");
    });
});

Demo

Upvotes: 1

Amit Joki
Amit Joki

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

Nis
Nis

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

Related Questions