-1

I have written below code of HTML

<ul class="dropdown-menu"> 
<li><button type="button" id="1" class="highlight"> Edit </button> </li>
<li><button type="button" id="2" class="highlight"> Edit </button> </li>
<li><button type="button" id="3" class="highlight"> Edit </button> </li>
<li><button type="button" id="4" class="highlight"> Edit </button> </li>
...............................

<li><button type="button" id="100" class="highlight"> Edit </button> </li>
</ul>

Now I want to fetch particular id in jQuery. But it's not working.

$('.highlight').on('click', function(e){
     var id = $(this).attr('id');
     alert(id); 
});

Edit added snippet to show code works fine:

$('.highlight').on('click', function(e) {
  var id = $(this).attr('id');
  console.log(id);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<ul class="dropdown-menu">
  <li><button type="button" id="1" class="highlight"> Edit </button> </li>
  <li><button type="button" id="2" class="highlight"> Edit </button> </li>
  <li><button type="button" id="3" class="highlight"> Edit </button> </li>
  <li><button type="button" id="4" class="highlight"> Edit </button> </li>
  <li><button type="button" id="100" class="highlight"> Edit </button> </li>
</ul>
freedomn-m
  • 27,664
  • 8
  • 35
  • 57
  • It should work, try to use `console.log(id)` in place of `alert(id)`, could it be that you have alerts disabled? – user2314737 Nov 14 '22 at 09:24
  • @user2314737 `console.log(id)` not working. – Rumman Ansari Nov 14 '22 at 09:30
  • You code, as provided, works fine. I've added a snippet to confirm. There could be a number of reasons - first **check browser console for errors** such as `$ not defined` - if any errors, report back here with details. Second, you may be building the `ul` after your `.click(()=>` code has run - `$(".highlight")` will only work on elements that exist at the time the code runs. Try `$(document).on("click", ".highlight", function() { console.log(this.id); })` - does that fix it? – freedomn-m Nov 14 '22 at 10:31

1 Answers1

0

You can try here and see that your code is working

$('.highlight').on('click', function(e){
     var id = $(this).attr('id');
     alert(id); 
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul class="dropdown-menu"> 
<li><button type="button" id="1" class="highlight"> Edit </button> </li>
<li><button type="button" id="2" class="highlight"> Edit </button> </li>
<li><button type="button" id="3" class="highlight"> Edit </button> </li>
<li><button type="button" id="4" class="highlight"> Edit </button> </li>
<li><button type="button" id="100" class="highlight"> Edit </button> </li>
</ul>

If the button is dynamically added, make sure to do it this way : Creating Dynamic button with click event in JavaScript

Reynadan
  • 649
  • 4
  • 18