Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

204
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda