1

I'm creating tabs in website.
Now I have a html code:

<button class="tablinks" onclick="openCity(event, 'Paris')">Paris</button>

where event is "var event : Event" and javascript:

        function openCity(evt, cityName) {
            var i, tabcontent, tablinks;
            tabcontent = document.getElementsByClassName("tabcontent");
            for (i = 0; i < tabcontent.length; i++) {
                tabcontent[i].style.display = "none";
            }
            tablinks = document.getElementsByClassName("tablinks");
            for (i = 0; i < tablinks.length; i++) {
                tablinks[i].className = tablinks[i].className.replace(" active", "");
            }
            document.getElementById(cityName).style.display = "block";
            evt.currentTarget.className += " active";
        }

It works fine with html, but I want to pass parameters from database. I tried with php code:

        foreach ($results as $item) {
            $mapName = $item['name'];
            echo "<button class='tablinks' onclick='openCity('event'," . $mapName . ")'>" . $mapName . "</button>";
        }

But tabs in php does not work, because event is not passed correctly. How to pass event into that function from php?

  • 1
    You should not use inline listeners at the first place, take a look ex. at https://stackoverflow.com/questions/65733674/how-to-give-php-variable-to-javascript , it shows you how to pass data from PHP to JS correctly. Then attach the events to the elements using [addEventListener](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener). Apart from that, you're going to get into troubles with live HTML collections, use `.querySelectorAll` to get a static list, or convert the live collection to array, and iterate the array instead of the collection. – Teemu Feb 27 '21 at 10:13

0 Answers0