Skip to content
Advertisement

Make paragraph change onclick from different buttons on HTML

I have 12 or so buttons on my HTML, and I want to change the text of just one paragraph after I click each button, because each button should deliver a different text. The problem is that, because I generated all the buttons through a Jinja loop (I’m running server in Flask) I only get the text from the LAST iteration of the loop, no matter which button I click. As you can see, I created the function that does the magic, but I don’t know where to place it so I can get the text from each button separately. I hope this is not too obvious and someone’ll be kind enough to respond. Please consider that I’m studying Python, so I’m below noob level on all things JS. Thanks a lot!

<table class="table">
      <tr>
          {%for i in days: %}
          <td>
              <table>
                  <tr>
                      <th>
                          {{ days[i] }}
                          <hr class="zero">
                      </th>
                  </tr>
                  {%for x in tasks: %}
                  {%if x.owner_id == i: %}
                  <tr>
                      <td>
                          <button  class="click" onclick="change_text()">{{ x.task_name }}</button>
                          <hr class="zero">
                      </td>
                  </tr>
                  {%endif%}
                  <script>
                  function change_text(){
                      document.getElementById("demo").innerHTML = "{{ x.task_id }}";
                  }
                  </script>
                  {%endfor%}
              </table>
          </td>
          {%endfor%}

Advertisement

Answer

Your function change_text needs a parameter where you can pass the text.

<script>
   function change_text (text) {
      document.getElementById("demo").innerHTML = text;
   }
</script>

Than you can write in your loop

{%for x in tasks: %}
{%if x.owner_id == i: %}
<tr>
  <td>
      <button  class="click" onclick="change_text('{{ x.task_name }}')">{{ x.task_name }}</button>
      <hr class="zero">
  </td>
</tr>
{%endif%}
{%endfor%}

Also you should define your JS function not within a Jinja loop but outside.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement