0

I am trying to create a dynamic Bootstrap dropdown button when the page load using this function

function loadPage(){

  var fType = $('<div class="btn-group" style="padding: 5px; width: 100%;"><button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown" style="width:100%">Category<span class="caret"></span></button><ul class="dropdown-menu" role="menu"><li><a href="#" id="act1">Action</a></li><li><a href="#" id="act2">Action 2</a></li></ul>');
  $("#col1").append(fType);

}

But when I try to add onclick event on one of the options it doesn't work! This is my javascript

    $('#act1').click(function(e) {
       e.preventDefault();
       alert('alerted');
});

Thanks.

1 Answer 1

1

Since content is new to DOM, you must init the click listener AFTER you load the button.

function loadPage() {
    var fType = $('<div class="btn-group" style="padding: 5px; width: 100%;"><button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown" style="width:100%">Category<span class="caret"></span></button><ul class="dropdown-menu" role="menu"><li><a href="#" id="act1">Action</a></li><li><a href="#" id="act2">Action 2</a></li></ul>');
    $("#col1").append(fType).promise().done(function () {
        $('#act1').click(function (e) {
            e.preventDefault();
            alert('alerted');
        });
    });
}
Sign up to request clarification or add additional context in comments.

1 Comment

Nice! Simple yet beautiful.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.