views:

176

answers:

2

I am trying to use the progress bar for a non-traditional purpose. I want to use the functionality to display a horizontal bar graph of two values retrieved from a database.

My PHP/MySQL/JQuery:

// retrieve results for display
$query = mysql_query(" SELECT furniture_purchases, electronics_purchases FROM sales WHERE store_id = $storeId ");
$sales = mysql_fetch_array($query);
$furniture = $ratings[0];
$electronics = $ratings[1];

echo ("<script type='text/javascript'>
            // display sales results
            $(document).ready(function() {
                $('div.furnitureBar').progressbar({ value: $furniture });
                $('div.electronicsBar').progressbar({ value: $electronics });
            });
        </script>");

My HTML:

<div class='furnitureBar'></div>
<div class='electronicsBar'></div>

Now the problem is, say if 101 furniture items were sold, the progress bar for furniture will fill the entire space since 100 is the max value according to JQuery progressbar documentation: http://jqueryui.com/demos/progressbar/

Instead I want the two values to form dynamically as comparison to one another, so if 101 furniture items were sold and 90 electronics items were sold, then both bars should be in the middle instead of it seeming like 100 is the max number of sales possible. In fact there is no limit to the max number of sales.

I hope I make sense.

+1  A: 

You need to scale the values so they fit. Example:

$furniture = $ratings[0];
$electronics = $ratings[1];

$max = max($furniture, $electronics);
if ($max > 100){
   $furniture *= (100 / $max);
   $electronics *= (100 / $max);
}

This example determines whether one of the numbers is greater than 100, which would result in an overflow (for the progressbar). If it is, it calculates a ratio such that the highest number is now 100. Then, it adjusts the second number accordingly. If you need an integer value, simply round or apply an (int) cast to the values.

The math behind it:

Let's say $furniture is 104 and $electronics is 76. As you have pointed out, 104 won't work because jQuery UI progress bars only support values up to 100.

104 is greater than 76, so we calculate the ratio to adjust the values like this: 100/104 = 0.961538462. So;

0.961538462 * 104 = 100

0.961538462 * 76 = (rounded) 73

SimpleCoder
A: 

This is actually very easily done with tables that are filled to your desired percentage. Performance-wise, it'll beat the pants off the Jquery option.

An example from a site I did:

<td> 
  <div id="graph_grey"> 
     <div id="graph_self" style="width:62%;"></div> 
  </div> 
</td> 
bpeterson76