I have a div
container with 8 child div elements
which indicate a some color bars. Each div block contains a weight-age
of 12.5%
.
<div class="progress-stacked" id="progress-div">
<div class="progress-bar progress-bar-fail" style="width: 10%; margin-right: 11px;"></div>
<div class="progress-bar progress-bar-fail" style="width: 10%; margin-right: 11px;"></div>
<div class="progress-bar progress-bar-fail" style="width: 10%; margin-right: 11px;"></div>
<div class="progress-bar progress-bar-fail" style="width: 10%; margin-right: 11px;"></div>
<div class="progress-bar progress-bar-fail" style="width: 10%; margin-right: 12px;"></div>
<div class="progress-bar progress-bar-fail" style="width: 10%; margin-right: 12px;"></div>
<div class="progress-bar progress-bar-fail" style="width: 10%; margin-right: 12px;"></div>
<div class="progress-bar progress-bar-fail" style="width: 10%;"></div>
</div>
How would i replace the class progress-bar-fail
with progress-bar-success
for the value i get from API. For instance if i get 12.5, i want the first child to have progress-bar-success
instead of progress-bar-fail
.
If its 25
, then two child div should be replaced with progress-bar-success
instead of progrss-bar-fail
.
You can do something like this,
var value = 12.5;/*somevalue from your API*/
var targetindex = value/12.5;
targetindex = Math.floor(targetindex);
$(".progress-bar").each(function(i){
if(i<targetindex)
$(this).removeClass("progress-bar-fail").addClass("progress-bar-success");
});
Take a look here: http://jsfiddle.net/77Kvk/3/
See this fiddle for a working test function: http://jsfiddle.net/NEWrq/5/ .
I dropped the hard-coded weight-age in favor of having it figure it itself, based on the number of percentage bars that exist.
var testProgressUpdate = function(per)
{
var totalBars = $(".progress-bar").length;
var barsToModify = totalBars * (per / 100);
barsToModify = Math.round(barsToModify);
$(".progress-bar").removeClass().addClass("progress-bar").addClass("progress-bar-fail");
$(".progress-bar").each(function(i)
{
if (i >= barsToModify) return false;
$(this).removeClass("progress-bar-fail").addClass("progress-bar-success");
});
}
testProgressUpdate(50); // 4 bars
//testProgressUpdate(12.5); // 1 bar
//testProgressUpdate(13.5); // 1 bar
//testProgressUpdate(24); // 2 bars
Here's my attempt
function progressUpdate(value) {
var n = Math.floor(value / 12.5);
$(".progress-bar:lt(" + n + ")").removeClass("progress-bar-fail").addClass("progress-bar-success");
$(".progress-bar:gt(" + (n-1) + ")").removeClass("progress-bar-success").addClass("progress-bar-fail");
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.