views:

22

answers:

1

How might one handle making a progressbar update to 100% based on having one or more items from all 3 groups?

For instance if I have 20 fruits, 0 grains, and 2 vegetables, it should show 66/67%. If I have 1 or more items from each group, show 100%; and having only 1 or more of 1 group should show 33/34% complete. I'm not sure if I should round up, or use mod here. Definitely needs help...

$(document).ready(function($){ 

 $( "#progressbar" ).progressbar();

 var fruits = parseInt($("li#num-of-fruits").text());
 var veggies = parseInt($("li#num-of-veggies").text());
 var grains = parseInt($("li#num-of-grains").text());

 if (fruits > 0) { var fruitsMod = 1 }
 else { var fruitsMod = 0 }

 if (veggies > 0) { var veggiesMod = 1 }
 else { var veggiesMod = 0 }

 if (grains > 0) {var grainsMod = 1}
 else { var grainsMod = 0 }

 var foodSum = 33.33 * (fruitsMod + veggiesMod + grainsMod);

 $("#progressbar").progressbar("option", "value", Math.round(foodSum));

 $("<span>").attr("id", "food-amount").text($("#progressbar").progressbar("option", "value") + "%").prependTo("h3#completeness");

});

HTML is simply an empty div#progressbar. Progressbar is the jQuery UI plugin version.

+1  A: 

This should save you 6 lines and ~150 bytes:

var fruitsMod = (parseInt($("li#num-of-fruits").text()) > 0 ? 1 : 0);
var veggiesMod = (parseInt($("li#num-of-veggies").text()) > 0 ? 1 : 0);
var grainsMod = (parseInt($("li#num-of-grains").text()) > 0 ? 1 : 0);

var foodSum = (100 / 3) * (fruitsMod + veggiesMod + grainsMod);
jnpcl
Only thing I'd add is the radix argument to parseInt: `var fruitsMod = (parseInt($("li#num-of-fruits").text(), 10) > 0 ? 1 : 0);`
Ryan Kinal