Pablo Lionel Arturi
Pablo Lionel Arturi

Reputation: 65

Trying to sum from a jquery selector and update an element

I need to sum some text elements and update an input text, following is the far I could go:

This would be a correct example. I want to sum the text from within the <span> if the the <tr> contains the class ui-state-error

HTML

  <table>
<tr id="rp-10-1-1" class="ui-state-error" style="width:50px; height:50px;">
    <td><span id="pr-10-1-1">100</span><td>
  </tr>  
<tr id="rp-10-1-2" class="ui-state-highlight" style="width:50px; height:50px;">
  <td><span id="pr-10-1-2">200</span><td>
</tr>  
<tr id="rp-10-1-3" class="ui-state-error" style="width:50px; height:50px;">
  <td><span id="pr-10-1-3">300</span><td>
</tr>  
</tr>
</table>
<input type="text" id="sumhere">

JAVASCRIPT

        $( 'tr[id^="rp-"]' ).click(
          function() {

        $('tr[id^="rp-"]').each(function(data, val) {

            var rps = $(this).attr("id").split("-");


              if ($("#pr-" + rps[1] + '-' + rps[2] + '-' + rps[3]).hasClass("ui-state-error")) {
                console.log($("#pr-" + rps[1] + "-" + rps[2] + "-" + rps[3]).text());
              }
        });
         }
        );

Upvotes: 0

Views: 77

Answers (2)

DinoMyte
DinoMyte

Reputation: 8868

tr would td are not recognized as a valid html. If you wish to extract just the total of the span elements, you may do the following :

var total = 0;
$('span[id^=hp]').each(function() // selects span starting with id=hp
{
  total += parseInt($(this).text());
});

$("#sumhere").val(total);

Based on your updated HTML :

var total = 0;
$('tr[id^=rp-10-1] span').each(function() // selects span withing the tr element starting with id=rp-10-1
{
  if(!isNaN(parseInt($(this).text()))) // condition for safety check while converting text to interger.
   total += parseInt($(this).text());
});

$("#sumhere").val(total);

Example : https://jsfiddle.net/DinoMyte/7nhx26a2/3/

Upvotes: 3

Zulhilmi Zainudin
Zulhilmi Zainudin

Reputation: 9365

Demo: https://jsfiddle.net/zzaj1jye/

HTML:

<tr id="rp-10-1-1">
  <span id="hp-10-1-1" class="ui-state-error">10</span>
  <span id="hp-10-1-2" class="ui-state-error">20</span>
  <span id="hp-10-1-3" class="ui-state-error">30</span>
</tr>

<input type="text" id="sumhere">

JS:

$(function() {

  var total = 0;
  $('span').each(function() {
    if ( $(this).hasClass('ui-state-error') ) {
        total += parseInt($(this).text());
    }
  });

   $("#sumhere").val(total);

});

Upvotes: 1

Related Questions