Ads

Wednesday, 23 April 2014

SharePoint 2010 highlighting and colouring fields in a list

Scenario: You have a list of data with some fields that capture a Yes/No answer. We want to highlight Yes in green and No in red.


Example list we begin with:

Now edit the page. Site Action > Edit Page.
Now we can add a Content Editor Web Part (CEWP) to the page BELOW the list so we can add custom code:

Click into the main section of the content editor web part to make the Editing Tools ribbon appear, then click on the HTML icon and choose ‘Edit HTML Source’.
 
The script below searches for all table rows and check to see if they have a class of “ms-vb2” which is the class that list rows have. For each row we check the innerHTML for the word “Yes” and colour it green or “No” and colour it red.
Code:
<script type="text/javascript" language="javascript">
  var x = document.getElementsByTagName("TD") // find all of the TDs
  var i=0;
  for (i=0;i<x.length;i++)
  {
//find the TDs styled for lists
    if (x[i].className=="ms-vb2")
    {
                //find the data to use to determine the color
           if (x[i].innerHTML=="Yes")
            {
                // set the color
                     x[i].style.Color='green';
                }
           //find the data to use to determine the color
           if (x[i].innerHTML=="No")
                {
                // set the color
                     x[i]. style.Color='red';
                }
           } //end if
  } //end for
</script>
Copy the above script into the HTML source:
Now refresh the page or click away and come back to it. You should now see the words “Yes” in green and “No” in red.
This approach can be extended to change fonts, styles, background colours, anything that regular css can do.
Also note that this customisation is done on the list view. Meaning if you have multiple views you will have to add the web part & code to each one. But it also gives you the advantage of being able to edit each one individually.

No comments:

Post a Comment

Ads