DataTable: Change the class for a column conditionally

I have a Datatable with the following column:

{ title: "Status", data: "StatusName", class: "centered-text" }

I need to change the font color conditionally.  I created classes for each condition.  How could I change the class based on the data?  

Thank You,
Crystal RouseWeb Developer/Database AdminAsked:
Who is Participating?
zephyr_hex (Megan)Connect With a Mentor DeveloperCommented:
By DataTable, I assume you mean in C# ?

One way to do this would be to select the rows in the DataTable that meet you condition, and modify the class.

//find the rows that meet your condition
DataRow[] rows = myDataTable.Select("title Like 'A%'");

//loop over those rows and add a new class
//note:  myDataTable is updated by this as well
for(int i = 0; i < rows.Length; i ++)
      rows[i]["class"] = rows[i]["class"] + " myNewClass";

Open in new window

Crystal RouseWeb Developer/Database AdminAuthor Commented:
I'm using JavaScript and C#.  Trying to create a function to change the class based on the data.
zephyr_hex (Megan)DeveloperCommented:
ok, the code I gave you above is C#

If you want to change the class in JavaScript, then you actually would be modifying an HTML table (client side structure) and not a DataTable (server side stucture) because JavaScript is a client side language.
Crystal RouseWeb Developer/Database AdminAuthor Commented:
I need to write a JavaScript function that I can call when the page loads to change the font of a column based on the data.  I can figure out most of this, just don't know how to find the column. I can get the entire table's class to change, just not the individual column.
zephyr_hex (Megan)Connect With a Mentor DeveloperCommented:
Here is a Fiddle Demo.

Given the following HTML:

<table id="myTable">
      <th>Col 1</th>
      <th>Col 2</th>
      <th>Col 3</th>
<input type="text" id="myTxt" placeholder="input column number">
<input type="button" id="myBtn" value="Do It">
<span id="mySpan"></span>

Open in new window

.red {
  background-color: red;

Open in new window

You can access the column values and modify the CSS from jQuery:
$('#myBtn').click(function() {
  var colNum = $("#myTxt").val();
  if ($("#myTxt") === "") return;

  var col = $('#myTable tr > td:nth-child(' + colNum + '), table tr > th:nth-child(' + colNum + ')');

  $("#mySpan").before("<div id='myDiv'>Values from column:</div>");
  var span = "";
  col.each(function() {
    span = span + $(this).text() + " ";


Open in new window

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.