Donate

Bootstrap Table Cell Background Conditional Formatting

Lately I was working on a project that requires the Bootstrap Table cell by Wenzhixin to be filled with background color based from dynamic values similar to Power BI Conditional Formatting. The color density will change based from a value. Example is if the value is 0%, then the cell background is white. If value is 50% yellow. If 100% then dark orange. Other values will be calculated based on range percent. In order to achieve the task, you need to set the data-cell-style of the bootstrap table.
<th data-field="PercentValue" data-sortable="true" data-searchable="true" data-cell-style="PercentValueCellStyle">Percent %</th>
The function to set the background color is defined below.
function PercentValueCellStyle(value, row, index) {
	var classes = [];
	var percent = 0;
	var backColor = '';

	if (value == 0) {
		percent = 0;
	}
	else {
		percent = (value / 100).toFixed(1);
	}           

	backColor = GetColorFromPercentage(percent);

	return {
		css: {
			"background-color": backColor
		}
	};
}
The function to generate the background colors was based from a solution in Stackoverflow. I modified the function to initialize the colors inside the function definition.
function GetColorFromPercentage(pctInput) {

	//define colors here: #FFFFFF, #D9B300 (50%), #EB895F (100%)
	var percentColors = [
		{ pct: 0.0, color: { r: 255, g: 255, b: 255 } },
		{ pct: 0.5, color: { r: 217, g: 179, b: 0 } },
		{ pct: 1.0, color: { r: 235, g: 137, b: 95 } }];

	for (var i = 1; i < percentColors.length - 1; i++) {
		if (pctInput < percentColors[i].pct) {
			break;
		}
	}

	var lower = percentColors[i - 1];
	var upper = percentColors[i];
	var range = upper.pct - lower.pct;
	var rangePct = (pctInput - lower.pct) / range;
	var pctLower = 1 - rangePct;
	var pctUpper = rangePct;
	var color = {
		r: Math.floor(lower.color.r * pctLower + upper.color.r * pctUpper),
		g: Math.floor(lower.color.g * pctLower + upper.color.g * pctUpper),
		b: Math.floor(lower.color.b * pctLower + upper.color.b * pctUpper)
	};

	return 'rgba(' + [color.r, color.g, color.b].join(',') + ')';
};
And the table cell decorated with background colors will look similar to the screenshot provided. Notice how the background color changes based from the values on the table cell.
Bootstrap Table Cell Background Conditional Formatting
See my sample working fiddle: Bootstrap Table Cell Background Conditional Formatting

Comments

Donate

Popular Posts From This Blog

WPF CRUD Application Using DataGrid, MVVM Pattern, Entity Framework, And C#.NET

How To Insert Or Add Emojis In Microsoft Teams Status Message

Pass GUID As Parameter To Action Using ASP.NET MVC ContribGrid