Reputation: 106
I have a table structure like this
<tr>
<td class="pg4 monthlyP">Value1</td>
<td class="pg4 monthlyP">Value2</td>
<td class="pg4 monthlyP">Value3</td>
</tr>
</table>
I am fetching some values from an api (fetchApi) and storing those in v11, v12, v21, v22, v31, v32
What I want to achieve is
#1. to change the table td structure dynamically to
<td class="pg4 monthlyP">
<span class="new">$<span id="arm5yr11">1,337.86</span> / $<span id="arm5yr12">1,360.28</span></span>
</td>
<td class="pg4 monthlyP">
<span class="new">$<span id="arm5yr21">1,338.86</span> / $<span id="arm5yr22">1,361.28</span></span>
</td>
<td class="pg4 monthlyP">
<span class="new">$<span id="arm5yr31">1,339.86</span> / $<span id="arm5yr32">1,362.28</span></span>
</td>
I am doing this
jQuery('.pg4.monthlyP:eq(1)').html('<span class="twoRatesARM">$<span id="arm5yr11">1,337.86</span> / $<span id="arm5yr12">1,360.28</span></span>');
jQuery('.pg4.monthlyP:eq(2)').html('<span class="twoRatesARM">$<span id="arm5yr21">1,338.86</span> / $<span id="arm5yr22">1,361.28</span></span>');
jQuery('.pg4.monthlyP:eq(3)').html('<span class="twoRatesARM">$<span id="arm5yr31">1,339.86</span> / $<span id="arm5yr32">1,362.28</span></span>');
#2. to fill the api values by targetting respective span ids like this
document.getElementById("arm5yr11").innerHTML = v11;
document.getElementById("arm5yr12").innerHTML = v12;
document.getElementById("arm5yr21").innerHTML = v21;
document.getElementById("arm5yr22").innerHTML = v22;
document.getElementById("arm5yr31").innerHTML = v31;
document.getElementById("arm5yr32").innerHTML = v32;
Problem is #2 is not working. How can I resolve this?
Upvotes: 0
Views: 148
Reputation: 24638
One approach you can use is to put the API values in an array then you can use the .html(Function)
method to create all the content on the fly in a single step, like so:
//Let's say
const v11 = 1, v12 = 2, v21 = 3, v22 = 4, v31 = 5, v32 = 6;
//We can put these values in an array:
const arr = [v11, v12, v21, v22, v31, v32];
//And create the span elements and populate them as follows:
$('td.pg4.monthlyP')
.html(i => `<span class="new">$<span>${arr[2*i]}</span> / $<span>${arr[2*i+1]}</span></span>`);
//Let's say
const v11 = 1, v12 = 2, v21 = 3, v22 = 4, v31 = 5, v32 = 6;
//We can put these values in an array:
const arr = [v11, v12, v21, v22, v31, v32];
//And create the span elements and populate them as follows:
$('td.pg4.monthlyP')
.html(i => `<span class="new">$<span>${arr[2*i]}</span> / $<span>${arr[2*i+1]}</span></span>`);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr>
<td class="pg4 monthlyP">Value1</td>
<td class="pg4 monthlyP">Value2</td>
<td class="pg4 monthlyP">Value3</td>
</tr>
</table>
Upvotes: 1