Skip to content
Advertisement

How do I apply js code to each foreach element?

I have a php/html code where I iterate over services. And I create modal form by js, but js code is triggered only on the first element iterated over by foreach (php).

What can I do to have js process each element of the array?

Php/html

JavaScript

js code

JavaScript

Advertisement

Answer

The problem is because you’re using id attributes in a repeated code block, and id have to be unique within the DOM. Change that to a class attribute, use querySelectorAll() instead of getElementById() and then use a forEach() loop over the resulting collection. Something like this:

JavaScript
JavaScript
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement