Call Javascript function on click of dynamic tab

Tags: , ,



I am new to MVC and I have not written a lot of jQuery/JavaScript. I am trying to call a JavaScript function on click of a nav-tab. The nav-tabs are added to the page dynamically. I know the “name” of the specific tab which I need to call the function when clicked, but for the life of me, I cannot figure out where or how to add it. Below is the code that dynamically adds the tabs to the page:

        <ul class="nav nav-tabs  nav-tabs-line" role="tablist">
        @{
            for (var i = 0; i < Model.Tabs.Tabs.Count(); i++)
            {
                var n = Model.Tabs.Tabs[i];
                <li class="nav-item" style="@(n.isHidden == true ? "display:none;" : "")">
                    <a class="nav-link @(activeAdded == false && n.isHidden == false ? "active" : "")" data-toggle="tab" href="#@n.href" role="tab" aria-selected="true" id="@n.aId" style="@(n.isHidden == true ? "display:none;" : "")">
                        @n.name
                    </a>
                </li>
                if (activeAdded == false && n.isHidden == false)
                {
                    activeAdded = true;
                    tabstr += "$('#" + @n.href + "').addClass('active');$('#" + @n.aId + "').click();";
                }
                if (n.isHidden == true)
                {
                    tabstr += "$('#" + @n.href + "').css('display','none');";
                }
            }
        }
    </ul>

I need to call the function loadRequests() when the tab named “Support” is clicked. Any assistance is greatly appreciated.

Answer

You can use event delegation on the parent <ul>.

$('ul.nav').on('click', '.nav-item:contains("Support")', function(e){
    loadRequests();
    //do something else
});

$('ul.nav').on('click', '.nav-item:contains("Support")', function(e) {
  console.log('clicked');
  //do something else
});
$('button').click(function(e) {
  $('ul.nav').append(`<li class="nav-item">
                    <a class="nav-link" data-toggle="tab" href="#@n.href" role="tab" aria-selected="true" id="@n.aId">
                        ${Math.random() < 0.5 ? 'something else' : 'Support'}
                    </a>
                </li>`);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul class="nav nav-tabs  nav-tabs-line" role="tablist">
  <li class="nav-item">
    <a class="nav-link" data-toggle="tab" href="#@n.href" role="tab" aria-selected="true" id="@n.aId">
                        Support
                    </a>
  </li>
</ul>
<button>Add Tab</button>


Source: stackoverflow