2

I have a search box that helps a user locate things in our menu and it works really well except when the link is a modal link. The won't fire the modal event and I'm stuck on why that is. Here is the searchbox code:

    $('#txtSearch').on('keyup', function () {
        if ($(this).val() != "") {
            $('#menuSearchResults').html("");
            $("a.menuItem:contains('" + $(this).val() + "')").each(function () {
                if ($(this).data('toggle')) {
                    $('#menuSearchResults').append('<a href="#" data-toggle="modal" data-target="' + $(this).data('target') + '" id="' + $(this).prop('id') + '">' + $(this).text() + '</a><br>');
                } else {
                    $('#menuSearchResults').append('<a href="' + $(this).prop('href') + '">' + $(this).text() + '</a><br>');
                }
            });
        } else {
            $('#menuSearchResults').html("");
       }
    });

Everything looks correct to me so I'm at a loss why its not working.

EDIT:

Here is my click event for the button in question

$('#mnuCreateReport').on('click', function (e) {
    e.preventDefault();

    buildFormDialog('dlgCreateReport', 'Create Custom Report', '/form/report/create');
});
Eddie
  • 838
  • 1
  • 19
  • 42
  • Here's the generic jQuery answer: http://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements I don't know how well it applies when using Bootstrap. – Barmar May 20 '15 at 20:48
  • I'm using on() for the link click event which is why I'm confused as to why its not working. – Eddie May 20 '15 at 20:51
  • Please show the code that you're using for the click event on the link. There are two ways to use `on` -- one performs normal binding, the other performs delegation. You're probably using the binding version. – Barmar May 20 '15 at 20:53
  • It should be `$("#menuSearchResults").on("click", "a", function()...)` – Barmar May 20 '15 at 20:53
  • @Barmar, you helped me get the ball rolling on this I have that event look for both menuSearchResults and the link's event id and its working now. – Eddie May 20 '15 at 21:01

1 Answers1

1

It seems the problem is that you are binding to the click event before the element is added to the DOM. You can use jQuery's event delegation to solve the issue. So instead of:

$('#mnuCreateReport').on('click', function (e) {
    e.preventDefault();

    buildFormDialog('dlgCreateReport', 'Create Custom Report', '/form/report/create');
});

You would have:

$('#menuSearchResults').on('click', '#mnuCreateReport', function(e){
    e.preventDefault();

    buildFormDialog('dlgCreateReport', 'Create Custom Report', '/form/report/create');
});

See the jQuery docs here for more info on how event delegation works. Cheers!

Vince
  • 2,762
  • 1
  • 14
  • 26