0

Using Django, my buttons are created using a for loop and assigned values based on model values.

Based on which button is click, I want to update the "new_note_header" with the innerHTML of the button.

I have created the following JavaScript, which works but only when the first button clicked.

<script>
function ProjectSelect () {
    var x = document.querySelector('button').innerHTML;
    document.getElementById('new_note_header').innerHTML = x;
}

document.addEventListener('DOMContentLoaded', function () {
    document.querySelector('button').onclick = ProjectSelect;
});


</script>

<div class = project_container>
    {% for project in projects %}
        <button class = individual_project_container>
            {{ project }}
        </button>
    {% endfor %}
</div>
<div class = note_header_container>
    <div class = new_note_header, id = new_note_header>
        New Note
    </div>
</div>

I would be grateful for any help in adapting the JavaScript so it works for all buttons clicked.

Sunderam Dubey
  • 1
  • 11
  • 20
  • 40
RoyKeane94
  • 43
  • 6
  • Add the click listener to `.project_container`, in the listener function, check that a button was clicked and do what you need. This is called [event delegation](https://stackoverflow.com/questions/1687296/what-is-dom-event-delegation). FYI, never omit attribute quoting from HTML. – Teemu Jun 02 '22 at 11:28
  • Thanks Teemu - very silly question but what do you mean by attribute quoting please? – RoyKeane94 Jun 02 '22 at 15:10
  • Attribute values in tags need quotes, just check how mplungjan has quoted the class names and ids. – Teemu Jun 03 '22 at 04:07

1 Answers1

1

querySelector will take the FIRST element that satisfies the selector

You could use querySelectorAll and assign a click event handler to each, but I recommend using delegation:

document.addEventListener('DOMContentLoaded', function() {
  const nnHead = document.getElementById('new_note_header');
  document.getElementById("project_container").addEventListener("click", e => {
    const tgt = e.target.closest("button");
    if (!tgt.matches(".individual_project_container")) return; // not a button
    nnHead.textContent = tgt.textContent.trim();
  });
});
<div class="project_container" id="project_container">
  <button class="individual_project_container">Project 1</button>
  <button class="individual_project_container">Project 2</button>
  <button class="individual_project_container">Project 3</button>

</div>
<div class="note_header_container">
  <div class="new_note_header" id="new_note_header">
    New Note
  </div>
</div>
mplungjan
  • 169,008
  • 28
  • 173
  • 236