Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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%}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading