Patch
Patch

Reputation: 754

JQuery - adding multiple values to a single element in a table

I am using flask. I pass 4 different lists into the HTML file, loop through them and put their value in the table

{% for (s_pid, s_name, s_cpu_percent, s_memory_percent) in zip(pid, name, cpu_percent, memory_percent)%}
          <tr>
            <td id="task-pid">{{s_pid}}</td>
            <td id="task-name">{{s_name}}</td>
            <td id="task-cpu-percent">{{s_cpu_percent}}</td>
            <td id="task-memory-percent">{{s_memory_percent}}</td>
          </tr>
{% endfor %}

It looks great and I can see every value in the table clearly

I need to update these values every 5 seconds and for that, I am using jquery (using ajax just to get the updated value and put in the values below e.g var task_status_cpu_percent = data["task status cpu percent"];(list))

for(var i = 0; i< task_status_pid.length; i++){
      $("#task-pid").text(task_status_pid[i]);
      $("#task-memory-percent").text(task_status_memory_percent[i]);
      $("#task-name").text(task_status_name[i]);
      $("#task-cpu-percent").text(task_status_cpu_percent[i]);
    }

task_status_pid is a list, in fact, all of the task_status are lists in the same length but when the jquery code accrues it doesn't do anything! I tried using replaceWith and that didn't go well what happened is that all the values were on the first tab.

what do I need to do in order to go through all of the values in task-pd task-name etc' like it is on the loop ({% for (s_pid, s_name, s_cpu_percent, s_memory_percent) in zip(pid, name, cpu_percent, memory_percent)%})

Upvotes: 1

Views: 802

Answers (1)

mplungjan
mplungjan

Reputation: 177786

You need to use class or add a counter to the ID. IDs MUST be unique

So EITHER

{% set count = namespace(value=0) %}
{% for (s_pid, s_name, s_cpu_percent, s_memory_percent) in zip(pid, name, cpu_percent, memory_percent)%}
          <tr>
            <td id="task-pid{{count.value}}">{{s_pid}}</td>
            <td id="task-name{{count.value}}">{{s_name}}</td>
            <td id="task-cpu-percent{{count.value}}">{{s_cpu_percent}}</td>
            <td id="task-memory-percent{{count.value}}">{{s_memory_percent}}</td>
          </tr>
  {% set count.value = count.value + 1 %}
{% endfor %}

and then

 $("#task-pid"+i).text(task_status_pid[i]);

OR (recommended)

const $tasks = $(".task-pid");

for(var i = 0; i< task_status_pid.length; i++){
  $tasks.eq(i).text(task_status_pid[i]);
   ....
}

using <td class="task-pid" etc

Upvotes: 2

Related Questions