Max Pain
Max Pain

Reputation: 1237

Jquery mobile adding a button to a page not working

I am developing a jquery mobile app. I came across a problem where a dynamically added button will not work unless I use .trigger('create'); but even after adding the trigger even I still have the same problem. This question is asked many many time on this website but all of the answers suggests adding .trigger('create'); to the code. How can I fix this problem? This is my code:

var button = $("<a data-role="button" id="my_button">My Button</a>");
$("#my_div").append(button).trigger('create');

$("#my_button").on("click", function(){
    alert("clicked");
});

when I click the button nothing happen.

Upvotes: 1

Views: 66

Answers (2)

Omar
Omar

Reputation: 31732

When adding anchors dynamically, use .buttonMarkup() to create it. It is possible not to add data-role="button" when creating it using the aforementioned enhancement method.

$("#my_div").append($("<a/>", {
    id: "my_button",
        "data-role": "button"
}).text("Button").buttonMarkup({
    icon: "delete",
    iconpos: "notext"
}));

Binding event to dynamically created elements, should be delegated from document.

$(document).on("click", ".selector", function () {
  alert("clicked");
});

Demo

Upvotes: 1

Felix
Felix

Reputation: 38102

Change:

var button = $("<button data-role="button" id="my_button">My Button</button>");

to:

var button = $("<button data-role='button' id='my_button'>My Button</button>");

You're not create your button properly. Concatenate your HTML correctly and your code should work

Upvotes: 0

Related Questions