0

I am working on a .NET5 upgrade and while upgrading the code I found that my jQuery selector for classes are not working. It is a MVC project with razor pages.

In my view I have my script at the top and I call the menus items with anchor tags:

<script src="~/menu.js" type="text/javascript"></script>

<a href="#" class="menu-pop create_new_project" data-position="right" data-content="New Project" id="new-project">
   <i class="fa fa-edit"></i>
   <span>New Project</span>
</a>

then in my menu.js it is called like this:

$('.create_new_project').on('click', function (e) { ...do stuff});

Update Just found that if I redirect, to another page, it triggers. I can confirm that the scripts is present when you view the menu. There are also no errors in the developer console. I am really not sure what I am doing wrong.

I tried to use the id instead of the class and adding selectors:

$('#new-project').on('click', function (e) { ...do stuff});
$('#new-project').on('click', 'a', function (e) { ...do stuff});

The issue still persisted.

It is loaded in the DOM enter image description here

spmoolman
  • 403
  • 8
  • 20
  • Is the `.create_new_project` element available in the DOM when the page loads, or is it dynamically created? – Rory McCrossan Nov 26 '21 at 11:32
  • It is there, I will add an image. @RoryMcCrossan – spmoolman Nov 26 '21 at 11:35
  • Note that the image from the DOM inspector shows that the element exists, but not that it existed when the page first loaded. It's an important distinction when working with event handlers. As a test, try this instead: `$(document).on('click', '.create_new_project', function (e) { ...do stuff});` – Rory McCrossan Nov 26 '21 at 11:37
  • Thanks @RoryMcCrossan I will try that – spmoolman Nov 26 '21 at 11:51
  • Just before you're `.on` line add: `console.log($(selector).length)` change "selector" to your selector, eg "#new-project" - if it's zero (0) then your event has nothing to attach to *at that time* (hence add it directly before the event line) – freedomn-m Nov 26 '21 at 11:56

1 Answers1

0

Try instead this. $('body').on('click', 'a.myclass', function() { // do something });

here any (including dynamic) element will be triggered.

this link might be help full. => How do I attach events to dynamic HTML elements with jQuery?