Кнопки на нажатии функционируют с тем же идентификатором разных и разных атрибутов

У меня есть веб -страница HTML с образцом кнопок, как показано часть приложения Django, которое заполняет имя и город после вставки значений:

{% for person in page_obj %}
       <button id="NotifyBtn" name="person.FName" town="person.LName">Press Me</button>
{% endfor %}
<button id="NotifyBtn" name="Billy" town="Bob">Press Me</button>
<button id="NotifyBtn" name="Timmy" town="Tawin">Press Me</button>
<button id="NotifyBtn" name="Milly" town="House">Press Me</button>

тогда у меня есть JS, который выполняет следующее:

document.getElementById("NotifyBtn").addEventListener("click", function(){
            var name = this.getAttribute("name");
            var town = this.getAttribute("town");
            fetch("{% url 'alert_via_JSON_Response' %}", {
                method: "POST",
                headers: {
                    "X-CSRFToken": "{{ csrf_token }}",
                    "Content-Type": "application/json"
                },
                body: JSON.stringify({ message: "Hi there: " + `${name} born in ${town}`
                 })
                }).then(response => response.json())
                    .then(data => alert(data.status));
        });

в моем приложении Django у меня есть следующее:

def alert_via_JSON_Response(request):
    if request.method == 'POST':
        data = json.loads(request.body)
        message = data.get('message', "Error in sending email")
        return JsonResponse({"status": f"{message}"})
    return JsonResponse({"status": f"No Message"})

Прямо сейчас, когда я нажимаю на веб -страницу, только одна кнопка работает и отправляет ответ JSON на веб -страницу, она не работает, если я нажимаю другую кнопку после нажатия первой кнопки. Есть ли способ нажать каждую кнопку при необходимости и отобразить ответ JSON для каждой кнопки?

The way you have targeted your HTML elements is close, but incorrect. You should not be giving multiple elements the same id (read another answer here and see this article to find out more about why).

Having more than 1 element with same id will only return the first element, which is why only 1 button works.

To solve this issue, replace the id with class and modify your code to look like this:

Buttons

<button class="NotifyBtn" name="Billy" town="Bob">Press Me</button>
<button class="NotifyBtn" name="Timmy" town="Tawin">Press Me</button>
<button class="NotifyBtn" name="Milly" town="House">Press Me</button>

JavaScript:

let buttons = document.getElementsByClassName("NotifyBtn")
for(let i = 0; i < buttons.length; i++){
    let button = buttons[i]
    button.addEventListener("click", function(){
        var name = button.getAttribute("name");
        var town = button.getAttribute("town");
        fetch("{% url 'alert_via_JSON_Response' %}", {
            method: "POST",
            headers: {
                "X-CSRFToken": "{{ csrf_token }}",
                "Content-Type": "application/json"
            },
            body: JSON.stringify({ message: "Hi there: " + `${name} born in ${town}`
             })
            }).then(response => response.json())
                .then(data => alert(data.status));
    });
}

What this does is select all elements with class and return them as an array of elements. Then for loop each item in the array and attach the event listener to each of them.

Вернуться на верх