javascriptjquerybootstrap-5craftcms

Jquery on click works on one page doesn't work on another


dropdown click working on one page but not on another even though its the same component that these page load and same javaScript file

Here's the component

 <li class="nav-item dropdown">
            <a class="nav-link dropdown-toggle active" data-bs-toggle="dropdown" href="#" role="button" aria-expanded="false">Please Select A Fabric Range</a>
            <ul class="dropdown-menu">
                {% for fabricRange in fabricRanges %}
                <li>
                    <a class="nav-link dropdown-item" id="tab-{{ fabricRange.id }}" data-bs-toggle="tab" data-bs-target="#tabpane{{fabricRange.id}}" type="button" role="tab" aria-controls="tabpane-{{fabricRange.id}}" aria-selected="true">{{fabricRange.title}}</a>
                </li>
                {% endfor %}
            </ul>
        </li>

And JS

 $(".dropdown-menu").on("click", "a.nav-link.dropdown-item", function() {
    console.log("clicked")
    $(this).parents(".nav-item.dropdown").find("a.dropdown-toggle").html($(this).html())
})

I have used it in three pages, two works, one doesn't. the console.log() also works fine on the two pages but no response in third. Please Help


Solution

    1. First you need to verify whether dropdown-menu class exists or not. In case if it exists then you need to check whether it has nav-link dropdown-item class or not. So for this you need to check HTML of that element. Please follow below piece of code for this purpose.

      $(document).ready(function(){
      var count = 0;
      if ($(".dropdown-menu").length > 0) {
          $(".dropdown-menu").each(function(index, item) {
              count = count + 1;
              if(count !== 0){
                  console.log($(item).html());
                  console.log(item.innerHTML);
              }
          }); 
      }
      //alert("count-->"+count);
      console.log(count);})
      
    2. After verification, if you've everything mention in point 1 above and still click is not working then you have to verify if JQUERY is getting loaded correctly and in the same hierarchy as on other 2 pages.