aynaz aynaz - 28 days ago 7
jQuery Question

How to add the table td texts into progress values

I have progress bars in the third column of my table. And I replace the value of progressbar from td that I commented used, and max of the progress bar from td that I commented available.

Problem is code is when there are two progress bars my code does not work correctly an already shows the value of one.

How should I do ?

Here is my snippet :



$("table tr").each(function() {
var progress = $(this).find('td:eq(2) progress');
progress.val($(this).find('td:eq(1)').text())
progress.prop('max', $(this).find('td:eq(0)').text())
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table border="1">
<tr>
<td>30</td> <!--available-->
<td>4</td> <!--used-->
<td colspan="2"> <progress value="98" max="100"><div class="graph"></div></progress></td>
</tr>

<tr>
<td>20 <br/> 20</td> <!--available-->
<td>6 <br/> 5</td> <!--used-->
<td>
<progress value="50" max="100"><div class="graph"></div></progress><br/>
<progress value="50" max="100"><div class="graph"></div></progress>
</td>
</tr>
</table>




Dij Dij
Answer Source

you can do something like this:

$("table tr").each(function() {
  var children = $(this).children('td');    //get all td children of current tr
  var vals = $(children[1]).html().split('<br>');   //get an array of values by splitting on <br>
  var maxVals = $(children[0]).html().split('<br>');   //likewise get an array of max values by splitting on <br>
  var progressBars = $(this).find('progress');    // find all progress elements inside current tr.
  vals.forEach((val, index) => {     //iterate over vals array
      $(progressBars[index]).val(parseInt(val));     //use index to set val for correct progressBar
      $(progressBars[index]).prop('max', parseInt(maxVals[index]));
  })
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table border="1">
<tr>
<td>30</td> <!--available-->
<td>4</td> <!--used-->
<td colspan="2"> <progress value="98" max="100"><div class="graph"></div></progress></td>
</tr>

<tr>
<td>20 <br/> 20</td> <!--available-->
<td>6  <br/> 5</td>  <!--used-->
<td>
<progress value="50" max="100"><div class="graph"></div></progress><br/>
 <progress value="50" max="100"><div class="graph"></div></progress>
</td>
</tr>
</table>