简体   繁体   中英

Jquery alert not showing up when dropdown list item is clicked

I am trying to get an alert to pop up when an item in a dropdown is selected, the dropdown is populated with database items. I have followed a tutorial online for the jquery part of the code where the code worked fine and the alert popped up. Just wondering if anyone can help as to why its not working with my code? (the ajax part has nothing to do with my question)

            $(document).on('click', '.theclass', function() {
                var clicked = $(this).attr("id"); 
                alert(clicked);
            });

            });

    </script>

A few things:

You cannot link to an external JavaScript source library AND embed your own JavaScript in a single <script> element. You must use two <script> elements, like this:

 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"><script>

 <script>
        $(document).on('click', '.studentclass', function() {
            var clickeditem = $(this).attr("id"); 
            alert(clickeditem);
        });
</script>

Also, your code includes an extra }); at the end, which is a syntax error .

Next, because you are dynamically creating the element , it may be that the code to wire up the event handler is running before the element has been added to the DOM. In that case, event delegation is recommended. Even if the current code creates the element before the script runs, this is considered a best-practice to guard against this becoming a problem in the future, should your code structure change.

As the beginning of that article states:

Event delegation allows us to attach a single event listener, to a parent element, that will fire for all descendants matching a selector, whether those descendants exist now or are added in the future.

Change your code to:

$(document).on("click", ".studentclass", function() {
  var clickeditem = $(this).attr("id"); 
  alert(clickeditem);
});

Since we can't reproduce .php here, I'll show the working code with a static element.

 $(document).on('click', '.studentclass', function() { var clickeditem = $(this).attr("id"); alert(clickeditem); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="dropdown"> <button onclick="myFunction()" class="dropbtn">Find Student ></button> <div id="myDropdown" class="dropdown-content"> <input type="text" placeholder="Search.." id="myInput" onkeyup="filterFunction()"> <div id="studentdrop"> <div id='students1'> <a href="#" id="testing1" class="studentclass">student name</a> </div> <div id='students2'> <a href="#" id="testing2" class="studentclass">student name</a> </div> </div> </div> </div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM