JQuery: Synchronize two ASP.Net text boxes


jquery1

“The central concept behind jQuery is – find something, do something. More specifically, select DOM element(s) from an HTML document and then do something with them using jQuery methods. This is the big picture concept.” ___________________________Cody Lindley(jQuery Succinctly)

Introduction:

As the title suggests, this post is about interacting with two ASP.Net text boxes. If any change/interaction happens to one of the text boxes then we’ll try to do the same to the other text box, programmatically.

Live Demo & Code

Live demo here
Download code hereDownload

Designing the UI:

Let’s start with a new WebForm. The UI in this case requires only two multiline text boxes separated by some white spaces. To keep things simple we’ll concentrate on ‘how it works’ rather than ‘how it looks’. Now, the above quotation indicates that we need to find something and do something and thus it is a two step process. Here the ‘something’ is the text boxes and we can find them by their ids, class, tag, type etc. Particularly for this example we’ll employ the find by class trick. So, we need to mention same CssClass for both the text boxes and thing to notice is- this class may not exists at all.

<div>
     <asp:TextBox runat="server" ID="TextBox1" CssClass="sync" TextMode="MultiLine" Height="100px" />&amp;nbsp;&amp;nbsp;
     <asp:TextBox runat="server" ID="TextBox2" CssClass="sync" TextMode="MultiLine" Height="100px" />
</div>

Writing the Code:

In the script part, we’ll code for two things-

  • Synchronizing the text typed in to one text box with the other
  • Synchronizing the scrolling in both the text boxes

So, we will write two functions for these two specific actions. The first operation can be done on keyup event and the second with scroll event.

<script>
        $(document).ready(function () {
            $(".sync").keyup(function () {
                $(".sync").val($(this).val());
            });
            $(".sync").scroll(function () {
                $(".sync").scrollTop($(this).scrollTop());
            });
        });
</script>

Result:

As I already have said, we can demonstrate two operations

  • Typing anything in to one of the text box will result in displaying same text in the other text box, simultaneously.
  • Type few lines of code so that the scroll bar is visible. Now when we scroll any of the text boxes using either keyboard or mouse, other one will be scrolled automatically.

Explaination:

We have embedded our code inside $(document).ready() function as this function is executed after the DOM is loaded and before the page contents are rendered in to the browser. We can define a common function for both the textboxes with the use of CssClass name. The first action is defined inside the keyup event so that when we release the key the action will be performed. The action here is nothing but copying the content of the current text box to the other. The val() with no argument returns the value of the text box and when some argument is passed to it, sets the argument as value of that text box. I hope this made the thing very clear and further explanation is not required. Now consider about the second action. The scroll() event is fired when we try to scroll the content of text box either through key board or mouse. Again, scrollTop() with zero argument returns the current scroll position but, sets the scroll positions to a value same as the argument if called with an argument.

Conclusion:

Now we are able to develop a page with two text boxes which are synchronized upon typing text in to them or using the scroll bar. We can use more than two text boxes and it will still work as long as we use a common CssClass for them.

I hope you have enjoyed reading this post. Your feedback is very important to me.

Advertisements

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 &amp; 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();
    
    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.