Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

202
Views
How can I assign the var to the innerHTML of individual buttons when the buttons are created through a for loop?

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.

Many thanks

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!