javascript - I want to alert on when checkbox checked but this code is not working

one text

Solution:

First you should answer, if the @foreach loop works fine and renders the ul > li list correctly. I gues it works.

The JS Code

I've rewritten your code and it works even though there is a problem in your code. You really should use non-identical id attributes. You can use classes or what ever multiple times in different HTML tags, but not the id attribute. But this does not cause the problem. Have a look on the example:

Example (in plain JavaScript)

document.querySelectorAll('#location').forEach(locationEl => {
  locationEl.addEventListener('click', () => {
    document.querySelectorAll('input[name=location]:checked').forEach(el => {
      console.log('go');
    });
  });
});


/* 

  "Equivalent" to your jQuery Code:

  $(document).ready(function(){
        $("#location").click(function(){
           $("input[name='location']:checked").each(function(){
           alert("go");
       });
    });
  });

*/
<ul>
  <li>
    <input type="checkbox" name="location" id="location">
  </li>
  <li>
    <input type="checkbox" name="location" id="location">
  </li>
  <li>
    <input type="checkbox" name="location" id="location">
  </li>
  <li>
    <input type="checkbox" name="location" id="location">
  </li>
</ul>

Source