Blog Archives

Javascript: Thousand separator

We may use following javascript function to show numbers formatted with thousands separator.

Definition


function formatThousandPlace(orgNum) {
            arr = orgNum.split('.');    //split integer part & fractional part
            intPart = arr[0];           //store integer part in a variable
            fractionPart = arr.length > 1 ? '.' + arr[1] : '';  //store fractional part in a variable
            var rgx = /(\d+)(\d{3})/;   //regexp to find thousand place
            while (rgx.test(intPart)) { 
                intPart = intPart.replace(rgx, '$1' + ',' + '$2');  //replace integer part after inserting a comma in the thousandth place
            }
            document.write(intPart + fractionPart); //write final value to the document
        }

Function Call
Now, we can use it anywhere in the document where we want to show those numbers. For example: it may inside normal html elements or some dynamic ASP.Net controls like GridView, DataList, FormView etc.

<script language="javascript">formatThousandPlace('10000000.00')</script>

While calling this from ItemTemplate of an ASP GridView the syntax will be

<asp:TemplateField HeaderText="Price">
    <ItemTemplate>
       <script language="javascript">formatThousandPlace('<%#Eval("SalePrice") %>')</script>
    </ItemTemplate>
</asp:TemplateField>

I hope this is helpful.

Javascript: Function to get current fiscal year

This can be useful when you need to print current session year or, current fiscal/financial year somewhere in your page and specifically when you do not want to invoke a server method for it.

Defining Function


<script language="javascript">
 function getCurrentFiscalYear() {
//get current date
 var today = new Date();
//get current month
 var curMonth = today.getMonth(); //get current month
 var fiscalYr = "";
 if (curMonth > 3) { //
 var nextYr1 = (today.getFullYear() + 1).toString();
 fiscalYr = today.getFullYear().toString() + "-" + nextYr1.charAt(2) + nextYr1.charAt(3);
 }
 else {
 var nextYr2 = today.getFullYear().toString();
 fiscalYr = (today.getFullYear() - 1).toString() + "-" + nextYr2.charAt(2) + nextYr2.charAt(3);
 }
 document.write(fiscalYr);
 }
 </script>

Calling Function

<script language="javascript">getCurSession()</script>

Note:

  • I have made the function as per Indian fiscal year. You can change it according to your country. You only need to modify the conditional statement i.e, if (curMonth > 3) where April(3) is the starting month of fiscal year.
  • getMonth() returns number of the month in a date value starting from 0 to 11
  • You can change this function to return the session year which can be input for another logic/function. Accordingly you have to change the function.

JavaScript Validation: Date Range

This quick post shows how to validate two date fields by comparing their values. When there is two date fields in a page like From Date & To Date , then generally arises a requirement to show a message that From Date can not be greater than To Date or, something like that. This is required when the user inputs a greater date in  the From Date field than To Date.

Example:

Here I have taken two TextBox for inputting dates named- txtFromDate & txtToDate


var FromDt = document.getElementById("<%=txtFromDate.ClientID %>").value;
var ToDt = document.getElementById("<%=txtToDate.ClientID %>").value;

if (Date.parse(FromDt.trim()) > Date.parse(ToDt.trim()))

{

alert("Please check date range!\nFrom Date cannot be greater than To Date!")

return false;

}

An alternate to CASE WHEN of SQL Server for few scenarios

Purpose of this quick post is to present an alternative way to CASE WHEN of SQL Server.

To execute the demonstration, take a look at the following example.


SELECT CustomerName,Address,Mobile FROM Customers ORDER BY CustomerName

This SQL query will retrieve the list of Customers from Customer table. Let Address and Mobile are the fields which allow NULL. It means the result of the query may return NULL for these two fields. Now we will use the result set returned by the above query to bind a Datalist or a Gridview.Let consider for Datalist, then we will use following code on .aspx page to bind these fields


Address : <%#DataBinder.Eval(Container.DataItem, "Address")%>

Mobile   :<%#DataBinder.Eval(Container.DataItem, "Mobile")%>

But, here problem is that when there is no data against one/both of these fields then on browser it will show nothing for the eval data. To avoid this we generally re-write the query using CASE WHEN as-


SELECT CustomerName,CASE WHEN Address IS NULL THEN '--Not Available--' ELSE  Address END AS  Address,CASE WHEN Mobile IS NULL THEN '--Not Available--' ELSE Mobile END AS Mobile FROM Customers ORDER BY CustomerName

The above query ensures that there is no blank space for the above said two field in the browser.

Now, for some scenario where I don’t want to set it from the server and I want an alternative then I may use Javascript to achieve this. Here the query will be same as the first query but change required on the .aspx code.

1.Declare a small Javascript method


function ReplaceEmptyFields(orig, repl) {

//orig : Origional string

//repl: String to be replaced with
 if (orig == "") {
 document.write(repl);
 }
 else {
 document.write(orig);
 }
 }

2.Call the above Javascript in place of Databinder as below

Address : <script language="javascript">ReplaceEmptyFields('<%#DataBinder.Eval(Container.DataItem, "Address")%>', "--Not Available--")</script>
Mobile : <script language="javascript">ReplaceEmptyFields('<%#DataBinder.Eval(Container.DataItem, "Mobile")%>', "--Not Available--")</script>

This will provide the same result as previous example using CASE WHEN. Few of the advantages of using this includes html formatting and style can be applied to the result. For example, if I’ll change the above code to show ‘–Not Available–’ in Gray color so that it will be more easy to read then the code on .aspx page will be like-


Address : <script language="javascript">ReplaceEmptyFields('<%#DataBinder.Eval(Container.DataItem, "Address")%>', "<font color='gray'>--Not Available--</font>")</script>
Mobile : <script language="javascript">ReplaceEmptyFields('<%#DataBinder.Eval(Container.DataItem, "Mobile")%>', "<font color='gray'>--Not Available--</font>")</script>

This post is based on my experience and experiments, so if you find something missing or, if you have a better idea then please share in  the comments.

Follow

Get every new post delivered to your Inbox.