Change text color based on field value (Details View)

I would like to change the text color from black to red if a field value in the details view page is “N/A”. I don’t want to change the label color, just the value.

Example: Field 1 = 1234 (text color black) / Field 1 = N/A (text color red)

I know that is a simple thing to do in on a table using display rules, but need some help with code for details page.

Thank you… JON

Hi Jon,

I’d be happy to help with your code.

So firstly, this will be handled with Javascript instead of only CSS, as the CSS depends on the current field value.

Knack uses a Javascript library called jQuery. Your jQuery needs to do the following steps:

  1. When the view is rendered, get the field value from the data parameter. Relevant article: View Render.
  2. Select the HTML element that holds the field value. Relevant article: jQuery Selectors
  3. If the field value is “N/A”, use the css() method to add a CSS style of color:red to the HTML element you selected in step 2. Relevant article: jQuery css() method

If you need the code to be more dynamic and apply to multiple views or multiple field values then there are additional steps, but your question only mentioned “N/A” on a Details view.

Hope this helps.

Thank you. Will give it a try.

Do you by chance have an example code you can share?

Here’s my “failed” attempt on this code. Any working revisions is greatly appreciated…

$(document).on(‘knack-view-render.view_187’, function(event, view, data) {
var fieldValue = $(“”).text().trim();
if (fieldValue === “N/A”) {
$(“p”).css(“color”, “red”);

You’re close. It will work with the following adjustments:

  • Set the CSS on .kn-detail-body instead of p. Selecting p means “select all the paragraph elements on the page” which we don’t want to do.
  • There’s a small typo in It should be like this: .field_267 .kn-detail-body with a period before the field and a space after. Relevant article: CSS Selectors

This should work:

$(document).on('knack-view-render.view_187', function (event, view, data) {
  var $field = $('#view_187 .field_267 .kn-detail-body')
  var fieldValue = $field.text().trim()

  if (fieldValue === 'N/A') {
    $field.css('color', 'red')

Dang it, I almost had it… Thank you, works as expected.