AdamMasters
AdamMasters

Reputation: 385

I'm trying to implement a click event on a bootstrap dropdown menu

Hi I have a bootstrap dropdown menu that is auto filled from a database. I am trying to get an event to happen when I click on one of the items in the menu. I have tried

$("body").on("click", ".ddBtnClick", function(event) { 
    console.log("Is it working? Yes!!");
});

with ".ddBtnClick" being a class assigned to each of the items in the list. but nothing happened. Here is the code to populate the list from a database.

$.getJSON("http://jeremiah.abrahamott.com/DadsCarsObjects.txt", function(data){
    $.each(data.aaData, function(i, option){
    $("#dropdownfill").append($('<li/>').append($('<a/>').attr("id", option.Year).attr("href", "#").attr("tabindex", "-1").addClass("ddBntClick").text(option.Make)))
    });
});

Here is the html for the dropdown.

<div class="row" style="margin-left:50px;">
            <div class="span3">
                <div class="btn-group">
                    <a class="btn dropdown-toggle" data-  toggle="dropdown" href="#">Make
                        <span class="caret"></span>
                    </a>
                    <ul class="dropdown-menu" role="menu" aria-labelledby="dropdownMenu" id="dropdownfill">

                    </ul>
                </div>
            </div>
    </div>

Upvotes: 4

Views: 1924

Answers (2)

qJake
qJake

Reputation: 17119

Have you tried wrapping your Javascript in the document.ready event?

$(function()
{
    $("body").on("click", ".ddBtnClick", function(event) {  
        console.log("Is it working? Yes!!");
    });
});

See the jQuery .ready() documentation for more information and examples.

Also, you should register the click event on the actual button and use .click() instead of .on():

$(function()
{
    $(".ddBtnClick").click(function(event) {  
        console.log("Is it working? Yes!!");
    });
});

Also, you have a typo:

.addClass("ddBntClick")

Should be:

.addClass("ddBtnClick")

Upvotes: 0

PSL
PSL

Reputation: 123739

Issue is with your className. You are registering the delegated event handler for ddBtnClick but actual class name is ddBntClick.

$("body").on("click", ".ddBtnClick", function(event) { 
    console.log("Is it working? Yes!!");
});

and

.addClass("ddBntClick");

Change the class name during construction or change in your event delegation.

$(function()
{
    $("body").on("click", ".ddBntClick", function(event) {  
        console.log("Is it working? Yes!!");
    });
});

Upvotes: 1

Related Questions