Changing a Control’s Background Color Based on its Value

You can customize the background color of a control using a computation action and CSS classes.

Sample Project

To view the sample for this task, import the advanced sample projects as described in Importing the Forms Advanced Samples. The sample form and CSS file for the task described in this section are contained in the forms.samples.controls project.

The form (SetBackgroundColorForControl.form) is at:

   forms.samples.controls/Forms/setBGColor/

The CSS file (custom.css) is at:

   forms.samples.controls/Presentation Resources/css/

You can double-click the form and CSS filenames (as well as those of other project resources) in the Project Explorer to open them in the editor. There, you can examine their contents and use them as models for your own projects.

Explanation

This topic covers the case where you want to apply a background color to a given control in a form based on the control’s value.

In order to implement this task, you will need to know:

  • How to specify a custom CSS document and refer it in the form.
  • How to add a computation action that is targeted to a property of the control

Procedure

  1. Create a form with one or more controls.
  2. Add following classes to the custom CSS document and refer to the document in the form
          .normalbg,
          {
             background-color: #808080;
          }
          .warningbg,
          {
             background-color: #00FF00;
          }
          .problembg,
          {
             background-color: #FF0000;
          }
  3. Add a computation action for the Style Class Name(s) property in the General Properties view for the form.

    Provide following JavaScript code for this action and select the update event of this control.

          var value = parseInt(control.textinput1.getValue());
          var bgclass = "normalbg";
          if ( value <= 100) {
             "normalbg";
          } else if ( value > 100 && value <= 500 ) {
             "warningbg";
          } else if ( value > 500 && value <= 1000 ) {
             "problembg";
          }
  4. Preview the form.

    Provide an integer value between 0 - 100 and the background color for the control is set to gray.

    Provide an integer value between 101 - 500 and the background color for the control is set to green.

    Provide an integer value between 501 - 1000 and the background color for the control is set to red.