Back to all How-tos

Dynamic image that doesn't contain the data field value

Sometimes, the data field value doesn’t contain the actual name of the image. So, we must proceed via scripting and use an if statement on the data field value.

For example, we have gift coupon to hand out to loyal customers. We have three images OLSG-Gift-1.jpgOLSG-Gift-2.jpg and OLSG-Gift-3.jpg corresponding respectively to the first, second and third coupons. These prizes depend on the invoice amount. The first coupon appears if the amount is greater than 20.000$. The second coupon if the amount is between 10.000$ and 20.000$ and third coupon for all other customers (they still deserve a small token of our appreciation!)

Steps

To achieve this, we will use a single image and set its path via scripting. You can use these resources to get started.

  1. Drag and drop the images in the images folder in the Resources pane
  2. Drag and drop an image in the document (for example, right after the invoice total)
  3. Assign an ID to this image in Attributes pane (e.g. dyn_image)
  4. Create a new script in the Scripts pane and open this script
  5. Set the find method to Selector and enter the image id #dyn_image in the Find text field.
  6. Write the code that constructs the path to the image and set this value to the ‘src’ attribute of the image. For better code, we use the if statement on the data field value. The script should look like this:
    var amount = record.fields.InvTotal;
    
        if(amount > 20000) results.attr("src", "images/OLSG-Gift-1.jpg");
        else if(amount > 10000) results.attr("src", "images/OLSG-Gift-2.jpg");
        else  results.attr("src","images/OLSG-Gift-3.jpg"); 

You can click on the Preview tab and browse through the different record to validate the proper functioning of the script.

Note: If you prefer to use external or network images instead of importing them to your document, check out our other how-to on resources!

Leave a Reply

Your email address will not be published. Required fields are marked *