В цикле Django работает только первая кнопка

div появляется только при нажатии на первую кнопку. Это работает так, как я хотел, но только для первой кнопки в цикле. Когда я вручную ставлю display = "block", он появляется хотя и на второй кнопке цикла. Я хочу переключить класс "bg-model", нажав на класс "editTime".

Любая помощь будет оценена по достоинству. Заранее спасибо...

HTML

<h4>Appointments</h4>
                    {% if upcomming_appointments %}
                        {% for d in upcomming_appointments %}
                        <li class="list-group-item d-flex justify-content-between align-items-center flex-wrap">
                            <h6 class="mb-0">
                                <ion-icon name="medkit"></ion-icon> Appointment with <strong>{{d.PatientName}}</strong><a class="btn btn-info "
                                    id="sessionBtn" href="{% url 'medicalReport' d.id %}">Start Session</a>
                            </h6>
                            <span class="text-secondary">
                                Date: <strong>{{d.appoitmentDate}}</strong> <br>
                                Time: <strong>{{d.appoitmentTime}}</strong><br>
                                Symptoms: <strong>{{d.symptoms}}</strong><br>
                                Comment: <strong>{{d.Comments}}</strong><br>
                            </span>
                            <a id = "changeTime" class="editTime">Change time</a>
                            <a class="btn btn-info " id="logoutBtn" href="{% url 'delete_appointment' d.id %}"
                                onclick="return confirm('Are you sure you want to cancel this appointment? This action is irreversible.')">Cancel
                                Appoitment</a>
                            <div class="bg-modal">
                                <div class="modal-contents">
                                    <div class="close">+</div>
                                    <form method="POST">
                                        <h5>Change Appointment Time</h5>
                                        {{d.id}}
                                        <input type="hidden" name="SessionID" value="{{d.id}}">
                                        <input type="time" id="timeChange" class="input" placeholder="Time">
                                        <button type="submit" class="loginBtn">Submit</button>
                                    </form>
                                </div>
                            </div>
                        </li>

JS

document.querySelector('.editTime').addEventListener("click", function() {
    document.querySelector('.bg-modal').style.display = "flex";
});

document.querySelector('.close').addEventListener("click", function() {
    document.querySelector('.bg-modal').style.display = "none";
});

views.py

def doctorProfile(request):
    upcomming_appointments = Appoitment.objects.all().filter(
        DoctorEmail=request.user, appoitmentDate__gte=timezone.now()).order_by('appoitmentDate')
    past_appointments = Appoitment.objects.all().filter(
        DoctorEmail=request.user, appoitmentDate__lt=timezone.now()).order_by('-appoitmentDate')
    g = request.user.groups.all()[0].name
    if g == 'Doctor':
        doctor_details = Doctor.objects.all().filter(EmailAddress=request.user)
        d = {'doctor_details': doctor_details,
             'upcomming_appointments': upcomming_appointments,
             'past_appointments': past_appointments}
    return render(request, 'doctorProfile.html', d)

Существует проблема с вашим шаблоном. Это происходит потому, что идентификаторы HTML строго уникальны, а поскольку вы перебираете циклы, идентификатор "changetime" дублируется, и поэтому работает только первая кнопка.

Обходной путь для этого заключается в том, что, во-первых, вы делаете идентификаторы уникальными, добавляя переменную, она может быть типа id="changeTime_{{d.id}}" или вы можете полностью удалить идентификатор, если он нигде не используется. Во-вторых, вы добавляете обработчик onClick к тегу.

Вы можете сделать следующее:

<a href id="your_id" class="editTime" onclick="showModal()">

в вашем js-файле:

function showModal() {
    document.querySelector('.bg-modal').style.display = "flex";
}
Вернуться на верх