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 >
<tr>
{%for i in days: %}
<td>
<table>
<tr>
<th>
{{ days[i] }}
<hr >
</th>
</tr>
{%for x in tasks: %}
{%if x.owner_id == i: %}
<tr>
<td>
<button onclick="change_text()">{{ x.task_name }}</button>
<hr >
</td>
</tr>
{%endif%}
<script>
function change_text(){
document.getElementById("demo").innerHTML = "{{ x.task_id }}";
}
</script>
{%endfor%}
</table>
</td>
{%endfor%}
CodePudding user response:
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 onclick="change_text('{{ x.task_name }}')">{{ x.task_name }}</button>
<hr >
</td>
</tr>
{%endif%}
{%endfor%}
Also you should define your JS function not within a Jinja loop but outside.
CodePudding user response:
Check this out
<script type="text/javascript">
function changeText(text) {
document.getElementById('demo').innerHTML=text;
}
</script>
<input type="button" value="Button 1" id="b1" onclick="changeText('First Button');"/>
<input type="button" value="Button 2" id="b2" onclick="changeText('Second Button');"/>
<input type="button" value="Button 3" id="b3" onclick="changeText('Third Button');"/>
<p id="pText">Click on a Button</p>