Solved

jQuery Calculate based columns text

Posted on 2016-07-31
6
32 Views
Last Modified: 2016-08-05
Hello Experts,

I need to perform something simple calculation yet when I look at my coding it seems quite long so i think there should be a better way, more pro :-)

I have a 7 columns table in the following structure:

01 | YELLOW | text | text | text | FREE
02 | BLUE | text | text | text | RESERVED
03 | BROWN | text | text | text | SOLD

There are many more COLORS ....

What I need to do using jQuery is:

1). Calculate how many YELLOW, BLUE, BROWN are listed (how many from each)
2). How many from each are FREE, RESERVED+SOLD (reserved+sold should be calculated as SOLD.)

I started like this but it is going to be pretty much long and i am not sure that's the most efficient way.

var TotalYellow = $('table td:contains("YELLOW")').size(); 
var TotalBLUE = $('table td:contains("BLUE")').size();
var TotalBrown = $('table td:contains("BROWN")').size(); var TotalRED = $('table td:contains("RED")').size(); $(TotalYellow).next().next().next().next().text(); ....

Open in new window

0
Comment
Question by:Refael
  • 3
  • 2
6 Comments
 
LVL 33

Assisted Solution

by:Slick812
Slick812 earned 250 total points
ID: 41736758
greetings   Refael, , , The problem I see with this is narrowing down your searches for the text entries in the <td>, you seem to have many colors, and several availiblity status, FREE- SOLD , , To do this in any efficien manner, I would think the best way was to do FOR LOOPS trough Arrays with the TEXT entries you are searching for, and in the COLORS array, have inner arrays that you can record the COUNT of the avail status. I not sure using jquery will make this easier, I do it without jquery like this -
<!doctype html><html lang="en"><head><title>Count Table TD</title>

<style>
body{background: #dfd;}
.pgTitle{text-align:center;color:#b50;}
#properies {width: 23em; border: 2px solid #2a2;background:#fed;}
#properies td {padding: 3px;}
#pReport{width:17em; border: 2px solid #2a2;min-height:4em;background:#fed;margin-top:4px;padding:5px;}
</style>
<script>
function countP(tid) {
  var colors = [["YELLOW",0,0,0,0],["BLUE",0,0,0,0],["RED",0,0,0,0],["BROWN",0,0,0,0]];
  var mrk = ["FREE","SOLD","RESERVED"];
  //var tlb = document.getElementById(tid);
  var trs = document.getElementById(tid).getElementsByTagName("tr");
  for (var r = 0; r < trs.length; ++r) {
    var tds = trs[r].getElementsByTagName("td");
    for (var c = 0; c < colors.length; ++c) {
      if (tds[1].innerHTML == colors[c][0]){
        ++colors[c][1];
        for (var m = 0; m < mrk.length; ++m)
          if (tds[5].innerHTML == mrk[m]) ++colors[c][m+2];
        }
      }
    }
	
var rep = "";
for (var c = 0; c < colors.length; ++c) 
  rep += colors[c][0]+", total= "+colors[c][1]+", free= "+colors[c][2]+", sold= "+(colors[c][3]+colors[c][4])+"<br>";

document.getElementById("pReport").innerHTML = rep;
}
</script>
</head>
<body><h3 class="pgTitle">Count Table TD</h3>
<button id="butCnt" onclick="countP('properies')">Count Properties</button>
<table id="properies">
<tr><td>01</td><td>YELLOW</td><td>text</td><td>text</td><td>text</td><td>FREE</td></tr>
<tr><td>02</td><td>RED</td><td>text</td><td>text</td><td>text</td><td>SOLD</td></tr>
<tr><td>03</td><td>BLUE</td><td>text</td><td>text</td><td>text</td><td>FREE</td></tr>
<tr><td>04</td><td>BROWN</td><td>text</td><td>text</td><td>text</td><td>RESERVED</td></tr>
<tr><td>05</td><td>YELLOW</td><td>text</td><td>text</td><td>text</td><td>RESERVED</td></tr>
<tr><td>06</td><td>RED</td><td>text</td><td>text</td><td>text</td><td>FREE</td></tr>
<tr><td>07</td><td>RED</td><td>text</td><td>text</td><td>text</td><td>SOLD</td></tr>
<tr><td>08</td><td>BROWN</td><td>text</td><td>text</td><td>text</td><td>FREE</td></tr>
<tr><td>09</td><td>BLUE</td><td>text</td><td>text</td><td>text</td><td>RESERVED</td></tr>
<tr><td>10</td><td>YELLOW</td><td>text</td><td>text</td><td>text</td><td>SOLD</td></tr>
<tr><td>11</td><td>YELLOW</td><td>text</td><td>text</td><td>text</td><td>SOLD</td></tr>
<tr><td>12</td><td>BLUE</td><td>text</td><td>text</td><td>text</td><td>FREE</td></tr>
<tr><td>13</td><td>RED</td><td>text</td><td>text</td><td>text</td><td>RESERVED</td></tr>
<tr><td>14</td><td>BROWN</td><td>text</td><td>text</td><td>text</td><td>FREE</td></tr>
<tr><td>15</td><td>BLUE</td><td>text</td><td>text</td><td>text</td><td>RESERVED</td></tr>
<tr><td>16</td><td>RED</td><td>text</td><td>text</td><td>text</td><td>SOLD</td></tr>
<tr><td>17</td><td>RED</td><td>text</td><td>text</td><td>text</td><td>RESERVED</td></tr>
</table>
<div id="pReport">No Count</div>
</body>
</html>

Open in new window


this works for me, and displays the result as -

YELLOW, total= 4, free= 1, sold= 3
BLUE, total= 4, free= 2, sold= 2
RED, total= 6, free= 1, sold= 5
BROWN, total= 3, free= 2, sold= 1
0
 

Author Comment

by:Refael
ID: 41736764
Hi Slick812

Thank you. but you are using JavaScript which is even harder for me.
I need to print each result (e.g. YELLOW, total= 4, free= 1, sold= 3) on a different place on that page.
I do not know what to do with your code :-(
0
 

Author Comment

by:Refael
ID: 41736779
And it counts well the total but nothing else...
0
What Should I Do With This Threat Intelligence?

Are you wondering if you actually need threat intelligence? The answer is yes. We explain the basics for creating useful threat intelligence.

 
LVL 33

Expert Comment

by:Slick812
ID: 41736785
OK sorry I posted then, but the description you gave in question, said nothing about what container you need the COUNT results in, and as you said -
"I need to print each result on a different place on that page",
does not mean much to someone deciding what code operations to use to get a result.

using arrays seems like the most efficient to me
0
 
LVL 51

Accepted Solution

by:
Julian Hansen earned 250 total points
ID: 41737059
Here is a JQuery solution. The solution loops through the <tr> elements of the table using $.each.
It retrieves the <td> elements in the row as an array.
From the <td> array it extracts the second and seventh cell value as text() to use as indices into the result array.
Results are stored in an array of objects each of which has a total value that is the total number of that colour found and then members for the total status values found for each colour.
Note the result array is not guaranteed to have a value for all status values - you can remedy this by adding initialisation code to the colour initialisation section of the code below. This will work if the status values are known before hand.
$(function() {
  // OUR RESULT ARRAY
  // THIS WILL BE USED TO STORE THE VALUES FOR THE TABLE
  // IT CAN BE USED TO ACCESS SPECIFIC COLOUR VALUES BY INDEX
  // DEFINED GLOBAL HERE BUT CHANGE TO SUITE YOUR CODE
  var result = [];

  // ITERATE THROUGH THE TABLE ROWS 
  // ADJUST TO TRIGGER ON EVENT AND TO MATCH YOUR TABLE
  $('tr').each(function() {

    // GET ALL THE <td> ELEMENTS IN THIS ROW INTO AN ARRAY
    var cells = $('td', this);

    // EXTRACT THE colour AND status VALUES FOR THIS ROW
    // TO USE AS indices INTO RESULTS ARRAY
    var colour = $(cells[1]).text();
    var status = $(cells[5]).text();
    
    // IF COLOUR DOES NOT EXIST
    // CREATE AND INITIALISE IT
    if (result[colour] == undefined) {
      result[colour] = {
        total: 0

        // POTENTIALLY ADD status INITIALISATION HERE IF 
        // ALL status VALUES ARE KNOWN
        // EXAMPLE
        // SOLD: 0,
        // WRAPPED: 0
       // ...
      }
    }

    // INCREMENT NUMBER OF colour FOUND
    result[colour].total++;

    // IF STATUS DOES NOT EXIST
    // CREATE AND INITIALISE IT
    // NB: IF YOU IMPLEMENTED THE status
    // INITIALISATION ABOVE THEN THIS IS POTENTIALLY NOT NECESSARY
    // ALTHOUGH PROBABLY GOOD IDEA TO KEEP IT TO CATCH ANY 
    // EXCEPTIONS WHERE A 'ROGUE' status MIGHT CREEP THROUGH
    if (result[colour][status] == undefined) {
      result[colour][status] = 0;
    }

    // INCREMENT NUMBER OF status FOUND
    result[colour][status]++;
  });

  // RESULT IS AN ARRAY INDEXED BY COLOUR
  // WITH MEMBERS FOR total AND EACH colour
  console.log(result);
});

Open in new window

Example Output
[]  
BLUE   Object { total=2,   RESERVED=1,   FREE=1}
  FREE     1
  RESERVED 1
  total    2
  wrappedJSObject Object { total=2,   RESERVED=1,   FREE=1}
BROWN   Object { total=4,   SOLD=2,   RESERVED=2}
  RESERVED 2
  SOLD     2
  total    4
  wrappedJSObject Object { total=4,   SOLD=2,   RESERVED=2}
  
YELLOW  Object { total=3,   FREE=2,   SOLD=1}
  FREE     2
  SOLD     1
  total    3
  wrappedJSObject  Object { total=3,   FREE=2,   SOLD=1}

Open in new window

0
 

Author Comment

by:Refael
ID: 41744014
Hello Slick812,  Hello Julian,

Thank you, you have always been so helpful. I decided, since the the solutions were sufficient to resolve my task is to actually hook up the database and perform queries for each. Yet thank you so much, always!
0

Featured Post

Top 6 Sources for Identifying Threat Actor TTPs

Understanding your enemy is essential. These six sources will help you identify the most popular threat actor tactics, techniques, and procedures (TTPs).

Join & Write a Comment

I found this questions asking how to do this in many different forums, so I will describe here how to implement a solution using PHP and AJAX. The logical flow for the problem should be: Write an event handler for the first drop down box to get …
International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
The viewer will learn how to dynamically set the form action using jQuery.
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)

707 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

17 Experts available now in Live!

Get 1:1 Help Now