• Ogłoszenie:

How can i fix button re-injection issue?

Wszystko odnośnie tworzenia grafiki - obróbka, problemy, oceny.
Tworzenia Stron internetowych - HTML, PHP, MySQL...

How can i fix button re-injection issue?

Postprzez MahilaTeekshna 31 Maj 2023, 05:32

reklama
I'm currently working on a booking web app and I'm facing an issue with adding the "active" class to buttons when clicked. The problem arises because these buttons are re-injected after being clicked, which causes the JavaScript to lose access to them.

To tackle this, I sought assistance from Chat GPT and received the following code snippet:

const buttons = document.querySelectorAll("#timeBtn");

buttons.forEach((button) => {
const isButtonClicked = localStorage.getItem(button.id);

if (isButtonClicked) {
button.classList.add("active");
}

button.addEventListener("click", () => {
button.classList.toggle("active");

const isActive = button.classList.contains("active");
localStorage.setItem(button.id, isActive ? "clicked" : "");
});
});
In my Twig file, here's the relevant section:

<h2 class="text-center">Midi</h2>

<ul class="d-flex flex-wrap justify-content-center mx-auto mt-3 list-unstyled text-small">
<div class="js-day" {% for index in time %} data-is-open="{{ index.isclosed ? 'false' : 'true' }}" {% endfor %}></div>

{% for reservation in availableDateAm %}
<li class="mx-1 my-1">
<a class="btn btn-outline-secondary lexend" id="timeBtn">{{ reservation | date("H:i")}}</a>
</li>
{% endfor %}
</ul>

<hr class="mt-5">

<h2 class="mt-1 text-center">Soir</h2>

<ul class="d-flex flex-wrap justify-content-center mx-auto mt-3 list-unstyled text-small">
{% for reservation in availableDatePm %}
<li class="mx-1 mt-1 my-1">
<a class="btn btn-dark lexend" id="timeBtn">{{ reservation | date("H:i")}}</a>
</li>
{% endfor %}
</ul>
The provided solution utilizes local storage to retain the information online2yu echat about whether a button was clicked. However, it appears that this solution is not working due to the re-injection of the buttons after being clicked.

Can you provide any clues or suggestions to resolve this issue? Thank you!
MahilaTeekshna
~user
 
Posty: 7
Dołączenie: 10 Kwi 2023, 10:03



Powróć do Grafika & Webmastering

Kto jest na forum

Użytkownicy przeglądający to forum: Brak zarejestrowanych użytkowników oraz 5 gości