0% found this document useful (0 votes)
58 views11 pages

Cog JS Cookbook 5

The document discusses using JavaScript to add dynamic functionality to Cognos reports. It provides examples of using JavaScript to: 1) Define a dynamic default value for a prompt by selecting the second option. 2) Change the title displayed for a value prompt. 3) Validate the format of user input in a textbox prompt, only submitting if it matches a regular expression.

Uploaded by

Harik C
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
58 views11 pages

Cog JS Cookbook 5

The document discusses using JavaScript to add dynamic functionality to Cognos reports. It provides examples of using JavaScript to: 1) Define a dynamic default value for a prompt by selecting the second option. 2) Change the title displayed for a value prompt. 3) Validate the format of user input in a textbox prompt, only submitting if it matches a regular expression.

Uploaded by

Harik C
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 11

Using JavaScript Files –

Tips and Tricks


In this chapter, we will cover the following:
ff Defining dynamic default values for prompts
ff Changing the title of the value prompt
ff Validating textbox prompts
ff Showing/hiding controls at runtime
ff Selecting and submitting values automatically
ff Manipulating the Date Time control
ff Creating a variable width bar chart using JavaScript

Introduction
Report Studio is a web-based tool and the reports designed in Cognos Report Studio are
accessed through a web browser. This allows us to do certain web page specific tasks,
for example, embedding our own HTML code or JavaScript files.
Often, business users need certain functionality which is not naturally available in Cognos
Report Studio. Hence, a new area has evolved in the Cognos Report Studio developer's
world—"JavaScripting".
With JavaScript, we can do certain manipulations on the objects used for prompt pages.
Please note that this was not officially introduced in the initial Cognos documentation.
However, lately many such techniques were published on the IBM website itself.
Using JavaScript Files – Tips and Tricks
70
In this chapter, we will look at some recipes that will teach you very useful and commonly
required functionalities achieved using JavaScript files. All these recipes are valid for IBM
Cognos 10. For Cognos 8, some code changes might be required. There are a lot of
examples and reading material is available for prior versions on the Internet.
After trying these recipes, you can build upon the ideas to write more sophisticated scripts
and do a lot more with your Cognos Reports. Please note that IBM doesn't directly support
these techniques and does not guarantee any upward or backward compatibility. However,
they are aware that developers are widely using them, and hence IBM will try to maintain
most of the objects, properties, and events in the future.
The level of JavaScript that we will be using in this chapter is basic. However, if you have
never used JavaScript before, I would recommend getting familiar with JavaScript basics
using books or online tutorials. The website http://www.w3schools.com/js is a good
source with a nice collection of samples and provides a quick tool to try your own scripts.
Please note that all the JavaScript-based recipes will need you to enable JavaScript in your
web browser. Usually, it is enabled by default.
Defining dynamic default values for prompts
Suppose that we have a report which allows users to select a shipment month. In our data
warehouse, the Time dimension (for shipment month) contains values up to the current
month. However, the business owners frequently select the prior month, so they want the
prompt to have the prior month selected by default.
Getting ready
Create a report that filters on the Shipment Month Key. Create a prompt page and add a
value prompt for the Shipment Month Key.
How to do it...
To achieve the requirements of the business owner, we will write a JavaScript code
that selects the second value from the top by default. In order to do this, perform the
following steps:
1. Open the prompt page in the report and select the value prompt. Adjust the sorting
property such that the Shipment Month Keys are populated in the descending order.
2. Let's start by adding an HTML item before the Shipment Month value prompt.
The HTML should be <span id = 'A1'>.
Chapter 3
71
3. Now add another HTML item after the Shipment Month value prompt. The HTML
should be </span>, as shown in the following screenshot:
4. Now add another HTML item to the prompt page.
5. Define the item as shown in the following code:
<script>
var theSpan = document.getElementById("A1");
var a = theSpan.getElementsByTagName("select"); /* This stmt
return an array of all value prompts within span */
for( var i = a.length-1; i >= 0; i-- ) /* now loop through the
elements */
{ var prompts = a[i];
if( prompts.id.match(/PRMT_SV_/))
{prompts.selectedIndex = 3; } /* This selects the second
options from top */
canSubmitPrompt();
}
</script>
6. Execute the report to test it.
How it works...
The logic used here is that we first sort the months in descending order and then select the
second option from the top. As the values populated from the database are up to the latest
month, the second value from the top will be the previous month.
As mentioned at the beginning of the chapter, Report Studio prompt pages are similar to any
other HTML pages with most of the controls being standard web controls. The HTML item in
Report Studio is a powerful component which allows us to embed our own code within the
page generated by IBM Cognos.
When we put a JavaScript within an HTML item, it is automatically executed when the
page loads.
Using JavaScript Files – Tips and Tricks
72
Span
With IBM Cognos 8.3, the report viewer architecture has been majorly changed. Before IBM
Cognos 8.3, it was common practice to define a NAME or ID for the prompt controls and use
that to manipulate controls at runtime through JavaScript.
However, from Version 8.3 onwards, the IDs of the controls are generated randomly and are
not fixed. So, it is a little difficult to get hold of a control. For this reason, we have defined a
span around the control that we want to manipulate.
By wrapping the control within the span tags, we will reduce the scope of our search
in JavaScript.
GetElementsByTagName
As we want to capture the value prompt within the span, we search for elements with the
select tag within the span A1.
If we want to perform the same operation on multiple value prompts, we can put them all
within the same span. The GetElementsByTagName function returns an array of elements
with the specified tag.
SelectedIndex
Once a value prompt object is captured in a variable, we can set its SelectedIndex property
to set the selection to the required value.
CanSubmitPrompt
In prior versions of Cognos, we used the CheckData() function to submit the prompt value.
This means Report Studio will accept the value and the adornments will disappear. However,
from Version 8.3 onwards, we can use a global CanSubmitPrompt() function for the
same purpose.
There's more...
A more suitable example of dynamic selection is iterating through the value prompt options
and selecting one based on a condition.
You can use the JavaScript functions to capture the system date and accordingly work out
the prior month. Then, traverse through all the values and select an appropriate one. Similarly,
you can iterate through all the prompt values and select the required entry based on value
instead of hard-coding selectedIndex to 3.
Chapter 3
73

Changing the title of the value prompt


In the previous example, the first line of the value prompt shows the data item name, that is,
Month key (ship date) as shown in the following screenshot:
The business owners want to change this to a more generic and user-friendly text.
Getting ready
We will use the report generated in the previous recipe.
How to do it...
We need to add a line to the JavaScript from the previous recipe to change the text of first
option (index 0). To do this perform the following steps:
1. Open the prompt page of the report created in the previous recipe.
2. Double-click on the HTML item that contains the JavaScript.
3. Replace the code with the following:
<script>
var theSpan = document.getElementById("A1");
var a = theSpan.getElementsByTagName("select");
for( var i = a.length-1; i >= 0; i-- )
{ var prompts = a[i];
if( prompts.id.match(/PRMT_SV_/))
{ prompts.selectedIndex = 3;
Using JavaScript Files – Tips and Tricks
74
prompts.options[0].text = 'Choose Shipment Month'; /*
This is the new line added to script */
}
canSubmitPrompt();
}
</script>
4. Run the report to test it as shown in the following screenshot:
How it works...
By default, the first line of a value prompt is the name of the data item. If you define the data
item expression within brackets, that is, ([Sales (query)].[Time (ship date)].
[Month key (ship date)]) in this example, then the first line of the value prompt is
populated by the parameter name.
However, there is no property within Report Studio that would allow us to put a custom title.
Hence, we are using JavaScript. We already know how to capture the prompt control using the
GetElementsbyTagName function. Once it is captured, we can manipulate the values. We
change the text property of the options[0] element to update the first line of the prompt.
Chapter 3
75
There's more...
You can also use the REMOVE() function to remove particular lines of a value prompt. It is
often useful to remove the first two lines (title and separator) using the following statements:
Prompts.remove(0);
Prompts.remove(1);
Prompts.removeAttribute("hasLabel");
Validating textbox prompts
Let's say there is a report with a textbox prompt. Users are expected to enter a phone number
in (nnn) nnn-nnnn format in that prompt.
In this recipe, we will write a code to validate the value entered by the user and submit the
report only if the value entered is in the specified format.
Getting ready
Pick any report and add a textbox prompt to it. We will add a JavaScript to validate that textbox.
How to do it...
We want to make sure that the user will write the phone number in the right format. So, we
will validate the number entered by the user using JavaScripts, and in case the number is
not following the required format, a warning message will appear to the user with the correct
format. To do this, perform the following steps:
1. Wrap the textbox prompt within a span in the same way as we did in prior recipes.
2. Add the following script to the page footer:
<script>
function ValidatePage()
{
var theSpan = document.getElementById("A1");
var a = theSpan.getElementsByTagName("input"); /* this
captures the textbox */
for( var i = a.length-1; i >= 0; i-- )
{
var link = a[i];
if( link.id.match(/PRMT_TB_/))
{phoneRegex = /^\(\d{3}\) \d{3}-\d{4}$/; /* This is
regular expression to allow only the strings in (nnn)
nnn-nnnn format */
Using JavaScript Files – Tips and Tricks
76
if( !link.value.match( phoneRegex ) ) {
alert( 'Please enter phone number in (nnn) nnn-nnnn
format' );
link.focus();
link.select();
return; }
else {promptButtonFinish();}
}
}
}
/* Following is standard code to get FormWarpRequest*/
var fW = (typeof getFormWarpRequest == "function"
?getFormWarpRequest() : document.forms["formWarpRequest"]);
if ( !fW || fW == undefined) { fW = ( formWarpRequest_THIS_
?formWarpRequest_THIS_ : formWarpRequest_NS_ );}
/* This returns all elements of Button tag */var buttons = fW.getE
lementsByTagName("BUTTON");
for (var i=0; i<buttons.length; i++)
{
if (buttons[i].id.match(/finish/)) // Capture the finish
button
{
if (buttons[i].onclick.toString().indexOf('finish') >
0)
{ buttons[i].onclick = ValidatePage;} /* This
overrides the FINISH button and attaches it to our function */
}
}
</script>
How it works...
We first define a function called ValidatePage() that captures the textbox value and
checks whether it follows the required format. We are using the match function of JavaScript
which allows us to parse the textbox string against our regular expression. The regular
expression ^\(\d{3}\) \d{3}-\d{4}$ allows only the string in (nnn) nnn-nnnn format.
Please note that there is a space in the phone number string format. If you forget this
space while trying the prompt, the number will not be considered as a correct entry.
You can read more about regular expressions and also try some on this website:
http://www.regular-expressions.info/javascriptexample.html.
Chapter 3
77
If the textbox value matches with our regular expression, we call the promptButtonFinish()
function to submit the prompt page. Otherwise, we show an error message and set the focus
back to the textbox.
Finally, this ValidatePage() function is attached to the Finish button by the second part of
the script. We capture the Finish button by its TagName (buttons) and ID match (/finish/)
and then override its OnClick event.
Showing/hiding prompt controls at runtime
Let's say a report shows sales quantity by product line and order method type. Users need to
filter on either product line or order method type, any one at a time.
They would like a facility to select which prompt they would want to filter on, and depending on
the selection, the prompt should appear.
Getting ready
Create a list report that shows product lines, order method types, and sales quantity.
Create two options filters—one on product lines and the other on order methods.
How to do it...
In this recipe, we will use JavaScript to control showing or hiding a prompt based on the
selection of another prompt. To do this, perform the following steps:
1. We will start by creating prompts for both the filters. For that, add a prompt page and
add two value prompts. Use the prompt wizard to connect them to the parameters
(product line and order method).
2. Set the Hide Adornment property of both the prompts to Yes.
Using JavaScript Files – Tips and Tricks
78
3. Now drag an HTML item just before the product line prompt. Define it as follows:
<Input type = radio Name = r1 title= "Click me to select
Product Line..." Value = "PL" onclick=
"radioSelect(this)">Product Line
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
<Input type = radio Name = r1 title= "Click me to select
Order Method..." Value = "OM" onclick=
"radioSelect(this)">Order Method
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
<span id = 'ProductSpan'>
4. Now add another HTML item between the product line prompt and order method
prompt. Define it as </span> <span id = 'OrderSpan'>.
5. Finally, add a third HTML item after the order method prompt. Define it as follows:
</span>
<script>
var fW = (typeof getFormWarpRequest == "function"
?getFormWarpRequest() : document.forms["formWarpRequest"]);
if ( !fW || fW == undefined) { fW = ( formWarpRequest_THIS_
?formWarpRequest_THIS_ : formWarpRequest_NS_ );}
var theSpan = document.getElementById("ProductSpan");
var a = theSpan.getElementsByTagName('select');
for( var i = a.length-1; i >= 0; i-- )
{ var ProductBox = a[i];
ProductBox.style.display = 'none'; }
theSpan = document.getElementById("OrderSpan");
a = theSpan.getElementsByTagName('select');
for( var i = a.length-1; i >= 0; i-- )
{ var OrderBox = a[i];
OrderBox.style.display = 'none'; }
function radioSelect(rad)
{ if (rad.value == "PL") /* Hide OrderBox and show
ProductBox */
{ ProductBox.style.display = '';
OrderBox.style.display = 'none';
}
else if (rad.value == "OM") /* Hide ProductBox and show OrderBox
*/
{ ProductBox.style.display = 'none';
OrderBox.style.display = '';
}
else /* Hide both controls */
{ ProductBox.style.display = 'none';
OrderBox.style.display = 'none'; }
}
</script>
Chapter 3
79
Now your prompt page will look like the following screenshot in Report Studio:
6. Run the report to test it. You will see two radio buttons. Depending on which one you
select, one of the prompts will be visible as shown in the following screenshot:
How it works...
This recipe works in three parts. First, we defined the radio buttons in the HTML item. This is
our own code, so we can control what happens when users select any of the radio buttons.
Before explaining how this recipe works, I would like the readers to know that
it is possible to achieve the required functionality using conditional blocks
instead of JavaScript. You would use the auto-submit functionality of the
radio button prompt, which will then cause the conditional block to show the
appropriate prompt.
Then, we wrapped both the prompts into spans so that we can capture them in the JavaScript
and manipulate the properties.
Finally, we wrote the JavaScript to toggle the display of prompts depending on the radio
button selection.
There's more...
When the prompt is hidden through the style.display property, the adornments aren't
hidden. That is why we set the adornments to off in step 2.
Using JavaScript Files – Tips and Tricks
80
When the visibility of a control is turned off, the control is still present on the form and the
selected value (if any) is also submitted in the query when the user clicks on the Finish button.
Hence, it is preferred that we reset the selection to index(0) when a prompt is hidden.
For information on how to select a value through JavaScript, please refer to the Defining
dynamic default values for prompts recipe of this chapter.
Selecting and submitting values
automatically
A business report has numerous prompts on the prompt page. Often, users want to run a
report for the latest month in the database, Camping Equipment product and E-mail as an
order method.
They want a facility to either manually select values for these prompts or alternatively run the
report for the previous selections on a single button click.
Getting ready
Create a list report with Product line, Order method, and Sales Quantity as columns.
Create optional filters on Product line, Order method, and the shipment month, that is,
Month Key (shipment date).
Create a prompt page with three value prompts for these filters.
How to do it...
In this recipe, we will add a custom button on the prompt page that will allow users to quickly
run the report for frequently used selections. To do this, perform the following steps:
1. We will start by wrapping the prompts within a span so that they can be captured
easily in JavaScript. Add one HTML tag before and one after each prompt to define
the spans. Define the spans as PL, OM, and SM for Product Line, Order Method, and
Shipment Month respectively. This is similar to the wrapping we have done in most of
the prior recipes.
2. Add one more HTML item on the prompt page after all the prompts and define it
as follows:
<script>
function defaultSelect()
{
var a = document.getElementById("PL");
var PL = a.getElementsByTagName("select");
Chapter 3
81
for( var i = PL.length-1; i >= 0; i-- ) /* Captures
Product Line prompt */
{
var PLBox = PL[i];
}
a = document.getElementById("OM");
var OM = a.getElementsByTagName("select");
for( var i = OM.length-1; i >= 0; i-- ) /* Captures Order
Method prompt */
{
var OMBox = OM[i];
}
a = document.getElementById("SM");
var SM = a.getElementsByTagName("select");
for( var i = SM.length-1; i >= 0; i-- ) /* Captures
Shipment Month prompt */
{
var SMBox = SM[i];
}
PLBox.selectedIndex = 2;
OMBox.selectedIndex = 2;
SMBox.selectedIndex = 4;
canSubmitPrompt();
promptButtonFinish();
}
</script>
<button type="button" onclick="defaultSelect()" class="bt"
style="font-size:8pt">Run for Defaults</button>
Now your prompt will look similar to the following screenshot in Report Studio:
Using JavaScript Files – Tips and Tricks
82
3. Run the report to test it. You should see a button that you did not see in Report
Studio. When you click on the button, it will automatically select the prompt values
and run the report as shown in the following screenshot:
How it works...
In this recipe, we are mixing two techniques learnt from previous recipes. In the Defining
dynamic default values for prompts recipe, we learnt how to capture a value prompt and
change its selection.
So, we are using the same technique here but instead of calling on Page Load, we are
calling the routine when users click on the button.
Then, we are also using a function, promptButtonFinish(), that we used in the Validating
textbox prompts recipe to submit the prompt.
The custom button is defined using the <button> tag, and as it is our own object, we can
easily make it call our JavaScript function for the on click event.
As mentioned in the Defining dynamic default values for prompts recipe, you will not
hardcode the selectedIndex in your script. Instead, you should traverse through all the
prompt selection options and choose one based on the value. For example, look for Camping
Equipment so that its order in the list won't matter.
Please refer to one such example on the IBM website at this URL:
http://www-01.ibm.com/support/docview.wss?uid=swg21343424 .
There's more...
This technique is very useful in real-life scenarios. You can define multiple buttons for different
frequently used selections. It saves time for users and makes the reports convenient to use,
especially when there are more than five prompts.
Chapter 3
83

Manipulating the Date Time control


There is a report that allows users to filter on Shipment Date Time using the Date Time
control. By default, Cognos selects the current date and midnight as the date and time.
Report Studio allows you to override this with another static default value. However,
a business will usually run the report for the end of the previous business day (5 pm).
In this recipe, we will learn how to change the default date and time for a Date Time control
to the end of the previous business day.
Getting ready
Create a dummy report that shows sales quantity by shipment day. Define a filter on
shipment day.
How to do it...
In this recipe, we want to change the default date and time for a Date Time control to the end
of the previous business day using JavaScript. To do this, perform the following steps:
1. We will start by adding a Date Time control to the report. For that, add a new
prompt page.
2. From Toolbox, drag Date & Time Prompt onto the prompt page. Connect it to the
Shipment Day filter using an appropriate parameter in the prompt wizard.
3. Now select the prompt and set its Name property to ShipmentDate as shown in the
following screenshot:
Using JavaScript Files – Tips and Tricks
84
4. Now add an HTML item to the prompt footer after the Finish button. Define it
as follows:
<script>
function subtractDay ()
{ var dtToday = new Date();
var dtYesterday = new Date( dtToday - 86400000 );
// NOTE 86400000 = 24 hours * 60 (minutes per hour) * 60
(seconds per minute) * 1000 milliseconds per second)
var strYesterday = [dtYesterday.getUTCFullYear(), dtYesterday.
getMonth()+1, dtYesterday.getDate()].join("-");
return strYesterday;
}
function subtractTime ()
{ var Time = "17:00:00.000"; return Time;
}
pickerControlShipmentDate.setValue( subtractDay() );
timePickerShipmentDate.setValue( subtractTime() );
</script>
5. Run the report to test it. You will see that the value of the Date Time control is set to
the previous day, which is 5 pm by default.
How it works...
Here we use standard JavaScript functions to work out the date of the previous day.
Please note that this date is computed based on the system date on the user's machine.
Then, we apply this date to the Date Time control using a pickerControl<name> object.
Also, we set the time to 5 pm using the setValue function of the timePicker<name> object.
You can similarly do more date and string manipulations to find First of Month, Last of
Month, and so on. I found the following script on the Internet for generating commonly
used dates:
<script language="JavaScript" runat="SERVER">
var today = new Date();
var thisYear = today.getYear();
var thisMonth = today.getMonth();
var thisDay = today.getDate();
function rw(s1, s2)
{
Response.Write("<tr><td>"+s1+"</td><td>"+s2+"</td></tr>");
}
Response.Write("<table border='1'>");
rw("Today:", today.toDateString());
Chapter 3
85
//Years
var fdly = new Date(thisYear - 1, 0, 1);
rw("First day of last year:", fdly.toDateString());
var ldly = new Date(thisYear, 0, 0);
rw("Last day of last year:", ldly.toDateString());
var fdty = new Date(thisYear, 0, 1);
rw("First day of this year:", fdty.toDateString());
var ldty = new Date(thisYear + 1, 0, 0);
rw("Last day of this year:", ldty.toDateString());
var fdny = new Date(thisYear + 1, 0 ,1);
rw("First day of next year:", fdny.toDateString());
var ldny = new Date(thisYear + 2, 0, 0);
rw("Last day of next year:", ldny.toDateString());
//Months
var fdlm = new Date(thisYear, thisMonth - 1 ,1);
rw("First day of last month:", fdlm.toDateString());
var ldlm = new Date(thisYear, thisMonth, 0);
rw("Last day of last month:", ldlm.toDateString());
rw("Number of days in last month:", ldlm.getDate());
var fdtm = new Date(thisYear, thisMonth, 1);
rw("First day of this month:", fdtm.toDateString());
var ldtm = new Date(thisYear, thisMonth + 1, 0);
rw("Last day of this month:", ldtm.toDateString());
rw("Number of days in this month:", ldtm.getDate())
var fdnm = new Date(thisYear, thisMonth + 1, 1);
rw("First day of next month:", fdnm.toDateString());
var ldnm = new Date(thisYear, thisMonth + 2, 0);
rw("Last day of next month:", ldnm.toDateString());
rw("Number of days in next month:", ldnm.getDate());
Response.Write("</table>");
</script>
Using JavaScript Files – Tips and Tricks
86
There's more...
You can write more sophisticated functions to work out the previous working day instead of
just the previous day.
You can mix this technique with other recipes in this chapter to tie the selection event with
the button click or radio buttons; that is, a particular date/time can be selected when a user
clicks on the button or selects a radio button.
Creating a variable width bar chart using
JavaScript
A report shows the Unit cost and Unit price of all products. It also works out the Profit
Margin from these two.
Business owners are naturally more interested in products with a high profit margin as well as
a high unit price.
Getting ready
Create a simple list report with Product, Unit cost, and Unit price as columns.
Also, add a calculated item called Margin to the list to compute the profit margin and define it
as follows:
([Unit price]-[Unit cost])/[Unit cost]
How to do it...
In this recipe, we will create a variable width bar chart using JavaScript that shows a bar for
every product. The length of bar will indicate the profit margin, whereas the width will indicate
the unit price. To do this, perform the following steps:
1. Drag a new HTML item onto the list report as a new column.
2. Unlock the report objects using the unlock button. Add four more HTML items in the
column where you added the HTML item in the previous step. The report should look
like the following screenshot:
Chapter 3
87
3. Now define the first HTML item as:
<script>
var barlen=100*((
4. For the second HTML item, set the Source Type to Data Item Value and select
Margin as Data Item as shown in the following screenshot:
5. Define the third HTML item as:
));
var barheight=((
6. For the fourth HTML item, again set the Source Type to Data Item Value. Select Unit
price as Data Item.
7. Define the fifth and last HTML item as:
)/10) ;
var myBar='<div style="background-color:blue; width:' +barlen+';
height:' + barheight +'"></div>' ;
document.write(myBar) ;
</script>
Using JavaScript Files – Tips and Tricks
88
8. Run the report to see the output. It will look like the following screenshot:
As you can see, Bugshield Lotion Lite has a huge profit margin. Canyon Mule Extreme
Backpack might have a relatively low profit margin, but its unit price is high, and hence
it is also an important product for the business.
In short, the area of the bar (width X height) indicates the importance of a product to
the business.
Chapter 3
89
How it works...
Report Studio has in-built chart objects which allow you to create sophisticated and detailed
charts. However, in this case, we don't have any complex charting requirements.
We just want to highlight the products with high profitability. The JavaScript used in this recipe
has the following structure:
<script>
var barlen=100*((length_driver)) ;
var barheight=((width_driver)/10) ;
var myBar='<div style="background-color:blue; width:' +barlen+';
height:' + barheight +'"></div>' ;
document.write(myBar) ;
</script>
We have split it into five HTML items so that the length_driver and width_driver can
be replaced with any data item from the query. We have used the Margin and Unit price,
but any other data item or calculation can be used as per the business requirement.
The multiplier (100) and divisor (10) are scaling factors as we need to scale the actual values
to pixels. We know that Margin is in percentage and the value range is approximately 0.5
to 30. Hence, we multiply it by 100 to get the bars in the range of 50 to 300 pixels long.
Similarly, Unit price is scaled down by 10 to get a bar width in the range of 5 to 50 pixels.
You can change the scaling to appropriate values in order to achieve nice looking bars.
There's more...
JavaScripts are executed on the client side within the web browser; hence there is no load on
the server to produce these charts.
However, please note that this technique is useful only when users are interactively using the
report in a web browser. Also, users must have JavaScripts enabled in their browser. It doesn't
work for PDFs, Excel sheets, or any output format other than HTML.

You might also like