Statistics
Visits: 105083
Page Visits: 139170
Active visitors (monthly): 5364
Feed Count: 45
Most visited page: Adding value as a technical analyst
Category : Javascript

A series of jQuery posts

I am an editor in http://DotNetKicks.com - a twitter like site that allows .Net enthusiasts to submit the latest .Net stories every day. Here are some interesting jQuery posts that I have written in the last month.

Using the AJAX UpdatePanel Control with jQuery:
http://blogs.dotnetkicks.com/vijayst/2011/08/using-the-ajax-updatepanel-control-with-jquery/

Writing a simple jQuery plugin for Watermarks:
http://blogs.dotnetkicks.com/vijayst/2011/08/writing-a-simple-jquery-plugin-watermark/

Review of a jQuery plugin for formatting numbers:
http://blogs.dotnetkicks.com/vijayst/2011/08/numberformatter-a-jquery-plugin/

Integrating jQuery UI with your ASP.NET application:
http://blogs.dotnetkicks.com/vijayst/2011/07/integrating-jquery-ui-with-your-app/

A comparision of AJAXControlToolkit with jQuery UI:
http://blogs.dotnetkicks.com/vijayst/2011/07/ajaxcontroltoolkit-vs-jquery/

Learn jQuery in 5 minutes:
http://blogs.dotnetkicks.com/vijayst/2011/07/learn-jquery-in-5-minutes/

If you like these stories, feel free to kick it. (a friendly term for appreciating an article). 

Permalink | No Comments | Leave your comment
 

Usability issues with jQueryUI datepicker widget

Datepicker is a one of the key widgets available in jQuery UI. For a demo, check the link: http://jQueryui.com/demos/datepicker

When you click on the textbox which is datepicker() enabled, it should open up a calendar. When the user selects a date, the calendar should go away. I have noticed that the widget has a few usability issues.

In IE 8+, when you click on the textbox and select a date from the calendar, the calendar does not go away. This is somewhat irritating. The workaround to this is that the user clicks on the page (other than the textbox).

In Chrome, the usability issue is slightly subtle. On selecting the date from the calendar, the calendar does disappear. But, what if the user wants to change the selection? When the user clicks the textbox again, the calendar does not popup.

My suggestion to developers is to show the button beside the textbox. This is available in the datepicker using the options provided. The default text in the button is "...". This can be changed. Also, for the UI designer, there is a neat option to embed an image within the button. The code to enable the button is shown below:


$('input[name$=txtDate]').datepicker({
    showOn: 'button',
    showButtonPanel: false,
    buttonText: 'Show'
});

 

Permalink | No Comments | Leave your comment
 

Move items from one listbox to another using jQuery

I have two listboxes - list1, list2. There are four buttons. Add button to move selected items from one listbox to another. AddAll button to move all items from one listbox to another. Remove and RemoveAll buttons do the reverse operation. The code below shows how this can be done using jQuery.

HTML


    <div>
        <asp:ListBox ID="list1" runat="server">
            <asp:ListItem Text="One"></asp:ListItem>
            <asp:ListItem Text="Two"></asp:ListItem>
            <asp:ListItem Text="Three"></asp:ListItem>
        </asp:ListBox>
        <asp:Button ID="btnAdd" runat="server" Text=">" />
        <asp:Button ID="btnAddAll" runat="server" Text=">>" />
        <asp:Button ID="btnRemove" runat="server" Text="<"/>
        <asp:Button ID="btnRemoveAll" runat="server" Text="<<" />
        <asp:ListBox ID="list2" runat="server"></asp:ListBox>
    </div>

Javascript


<script src="Scripts/jquery-1.4.1.js" type="text/javascript"></script>
<script type="text/javascript">
    $(document).ready(
        function () {
            $('#btnAdd').click(
                function (e) {
                    $('#list1 > option:selected').appendTo('#list2');
                    e.preventDefault();
                });

                $('#btnAddAll').click(
                function (e) {
                    $('#list1 > option').appendTo('#list2');
                    e.preventDefault();
                });

                $('#btnRemove').click(
                function (e) {
                    $('#list2 > option:selected').appendTo('#list1');
                    e.preventDefault();
                });

                $('#btnRemoveAll').click(
                function (e) {
                    $('#list2 > option').appendTo('#list1');
                    e.preventDefault();
                });
 
        });
</script>

The selector for selecting items in a listbox is $('list1 > option:selected'). AppendTo function moves item from one element to another. e.preventDefault prevents event bubbling so that the page is not posted back.

Permalink | 5 Comments | Leave your comment
 
Commented by Vijay at 08-Sep-2011 10:13 PM

@Manivannan, I want to investigate this a little bit more. There is also another requirement where moving a item from one listbox to another should not affect the sort order.

I intended this post to be a simple post which shows what can be done using jQuery. Since, there is some interest in this post, I will spend my time and make it better.

Commented by ManivannaN at 08-Sep-2011 11:19 AM

Hi Vijay..

In the code behind,Wen v trying to access the listbox item countin the target source.. it still showing zero..?? Do u hav any idea abt this issue..??

Commented by Arunshyam at 07-Sep-2011 06:58 PM

Really nice code...

Commented by Vijay at 15-Aug-2011 09:44 AM

There is no sort function readily available for listbox. One way to do this is to use the each() function for the listbox items. I will try to come up with another post on this when I find a neat solution.

Commented by vhinz at 11-Aug-2011 03:40 PM

Your code is good.. I love it. Anyway can you help me with this. Can we sort the listbox after moving it..

Updating textbox with checked items using jQuery

I have a CheckBoxList. When the user checks or unchecks the items in the CheckBoxList, a TextBox should be updated with the checked values separated by a comma. How can I do this?

You can open up the designer. Add a CheckBoxList and TextBox as shown below:


  <asp:CheckBoxList ID="CheckBoxList1" runat="server">
      <asp:ListItem>House</asp:ListItem>
      <asp:ListItem>Car</asp:ListItem>
      <asp:ListItem>Bike</asp:ListItem>
  </asp:CheckBoxList>
  Choice:
  <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
  

After adding the HTML, you can add a simple script using jQuery. The script will set up the click() handler of the checkbox to update the textbox as shown below:


$(document).ready(
    function init() {
          $.each($('input[name*=CheckBoxList1]'),
              function () {
                  $(this).click(
                      function () {

                          var txt = '';
                          $.each($('input[name*=CheckBoxList1]:checked'),
                              function () {
                                  txt = txt + $(this).val() + ',';
                              });
                          if (txt.length > 0)
                              txt = txt.substring(0, txt.length - 1);
                          $('input[name$=TextBox1]').val(txt);
                      });
              });
          }
      );

The selector for Checkboxes uses the [name*=CheckBoxList1]. This gets all input elements which has CheckBoxList1 embeeded within the name.

Permalink | 1 Comment | Leave your comment
 
Commented by srinivas at 19-Jan-2012 03:43 PM

Please leave your comment

Hi, thank you so much for your valuable code... Colud I except the code in the asp.net... I would greatly appreciate you..

Thank you..

Disable validation based on option

In a webpage, there are multiple validators and a dropdown. In the dropdown, if the option selected is Y, all validators should fire. If option selected is N, then all validators should be disabled. The server-side code is simple. How can this be done in javascript?

The HTML of the page looks like this:


 <asp:DropDownList ID="ddlList" runat="server" OnChange="ValidateIf();">
    <asp:ListItem Value="Y" Text="Yes"></asp:ListItem>
    <asp:ListItem Value="N" Text="No"></asp:ListItem>
</asp:DropDownList>
<asp:TextBox ID="txtName" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="val" runat="server" ControlToValidate="txtName"
                             ValidationGroup="Group1" Display="Dynamic"  
                             ErrorMessage="Please enter name" 
                             >
</asp:RequiredFieldValidator>
<asp:Button ID="btn" runat="server" Text="Submit" ValidationGroup="Group1" CausesValidation="true" />

When the dropdown is changed, then the javascript function - ValidateIf() is fired. This contains logic to enable / disable the validators. The function ValidatorEnable() is used for each validator


 function ValidateIf() {
    var list = document.getElementById('ddlList');
    var val = document.getElementById('val');
    
    if (list.options[list.selectedIndex].value == "Y") {
        ValidatorEnable(val, true);        
    }
    else {
        ValidatorEnable(val, false);
    }
}

Permalink | 2 Comments | Leave your comment
 
Commented by ray at 01-Oct-2010 07:33 AM
Javascript post #1
Commented by Shailendra at 29-Oct-2010 01:28 PM
What is special about this post?

ACT vs JQuery

ACT (AjaxControlToolkit) and JQuery offers gave UI flexibility for asp.net developers. ACT can be used for WebForms while JQuery can be used for ASP.NET MVC. Here are the equivalent controls in ACT and JQuery that are popular:

ACT TabContainer and JQuery Tabs

ACT CalendarExtender and JQuery DatePicker

ACT Accordion and JQuery Accordion

ACT ReorderList and JQuery Sortable

ACT ModalPopupExtender and JQuery Dialogs

The key difference between the two is that ACT is based on Microsoft AJAX client scripts whereas JQuery is purely javascript based and used by popular websites including Google.

Permalink | No Comments | Leave your comment
 

Reordering table rows on MouseMove

How can I move the rows of the table by dragging it?

The code below is self-explanatory with comments. It works in IE6

<table id="Grid"><tr onmousedown="holdRow(this);" style="position: relative;"><td width="400">
            Name 1
        </td><td width="400">
            Test
        </td></tr><tr onmousedown="holdRow(this);" style="position: relative;"><td>
            Name 2
        </td><td width="400">
            Test
        </td></tr><tr onmousedown="holdRow(this);" style="position: relative;"><td>
            Name 3
        </td><td width="400">
            Test
        </td></tr><tr onmousedown="holdRow(this);" style="position: relative;"><td>
            Name 4
        </td><td width="400">
            Test
        </td></tr></table>
The javascript for the above table is below:

<script type="text/javascript">


    var selRow = null;
    var selRowTop = 0;
    var selIndex = 0;
    var clientY = 0;
    var bgColor = "";

    var grid;

    function move() {

        if (selRow) {
            // Change the bgColor of row to gray
            selRow.bgColor = "Gray";
            // Move the row
            selRow.style.pixelTop = window.event.clientY - clientY;
    
            var top = selRowTop + selRow.style.pixelTop;
            
            // If the row is moved beyond table boundary, reset the row
            if (top > grid.offsetHeight) {
                selRow.style.pixelTop = 0;
                releaseRow();
            }
            if (top < 0) {
                selRow.style.pixelTop = 0;
                releaseRow();
            }
        }
    }


    function holdRow(row) {
        
        selRow = row;
        grid = document.getElementById("Grid");

        // Get the position of the selected row within the table
        for (var i = 0; i < grid.rows.length; i++) {
            if (grid.rows[i] == selRow) {
                break;
            }
            selRowTop += grid.rows[i].offsetHeight;
        }

        // Get the row index and store it in selIndex
        selIndex = i;
        bgColor = selRow.bgColor;

        // Store the initial position of the row in the screen
        clientY = window.event.clientY;
        
        // For moving the row, handle the onmousemove event of document
        document.onmousemove = move;
        document.onmouseup = releaseRow;
    }


    function releaseRow() {
        if (selRow) {
            // If the row is moved, adjust the position
            if(selRow.style.pixelTop!=0) {
                adjustGrid();
            }

            // Reset styling, variables and event handler
            selRow.bgColor = bgColor;
            bgColor = "";
            
            selRow = null;
            selRowTop = 0;
            selIndex = 0;
            document.onmousemove = null;
            document.onmouseup = null;
        }
    }

    function adjustGrid() {
        // Based on position, rearrange the table
        var pos = selRowTop + selRow.style.pixelTop;
        if (selRow.style.pixelTop > 0) {
            pos += selRow.offsetHeight;
        }
        
        var top = 0;
        var i = 0;
        // Get the new position of the row within the table
        for (i = 0; i < grid.rows.length; i++) {
            if (pos >= top && pos < (top + grid.rows[i].offsetHeight)) {
                    break;
                }
            top += grid.rows[i].offsetHeight;
        }

        if (selRow.style.pixelTop > 0) {
            i = i + 1;
        }

        // Reset the relative Top to zero but rearrange table
        selRow.style.pixelTop = 0;

        // Insert in the appropriate position
        // Else append to the end of the table
        // IE automatically removes the node from table and inserts!
        var ins = grid.childNodes[0].childNodes[selIndex];
        if (i < grid.rows.length) {
            var ref = grid.childNodes[0].childNodes[i];
            grid.childNodes[0].insertBefore(ins, ref);
        }
        else if (i = grid.rows.length) {
            grid.childNodes[0].appendChild(ins);
        }
    }
        
</script>

Permalink | 1 Comment | Leave your comment
 
Commented by adil at 21-Nov-2009 12:56 PM
In firefox rows are not moving and u provide css for table rows for easy to drag and move

RadioButtonList OnClick

I have a RadioButtonList. When the user selects the first RadioButton in the list, I want a textbox to be displayed. For all other RadioButtons, I want this textbox to be hidden. I want this behaviour to be consistent when the user presses the Back button after navigating out of the page

RadioButtonList is a table of RadioButtons having the same name. Each RadioButton has a OnClick event that we can handle in Javascript. Here is the code for hiding/unhiding the textbox on Radiobutton click


   <asp:RadioButtonList ID="lstRadio" runat="server">
    <asp:ListItem Text="Indv" Value="0" OnClick="toggle();"></asp:ListItem>
    <asp:ListItem Text="Entity" Value="1" OnClick="toggle();"></asp:ListItem>
   </asp:RadioButtonList>
   <asp:TextBox ID="txtDOB" runat="server"></asp:TextBox>

Note the OnClick on ListItem. The OnClick is a client-side event handler. The toggle() function is below:

function toggle() {
	var lst = document.getElementsByName('lstRadio');
        
	if (lst[1].checked == true)
            document.getElementById('txtDOB').style.display = 'inline';
        else
            document.getElementById('txtDOB').style.display = 'none';
            
    }

The Radio buttons with name - lstRadio can be got by document.getElementsByName(). The first radiobutton is the second element in the array or lst[1]. This is because the RadioButtonList server control renders the table holding the radiobuttons with the same name - lstRadio. Finally, to ensure that this behaviour is consistent across postbacks and back-button navigation, the body onload event handler should call the toggle() function. This ensures that the behaviour of the RadioButtonList is consistent.

<body onload="toggle();">

Permalink | 2 Comments | Leave your comment
 
Commented by Mike at 20-Oct-2009 06:41 AM
Thank you for your helpful blog posting. Watch, Learn Grow www.LearningVisualStudio.info
Commented by Vijay at 25-Oct-2010 01:11 AM

Thank you, Mike

ValidatorEnable Javascript function

I have a dropdownlist with different options like Name, Phone, Date etc. There is a textbox in which I enter values for these options. Each of these options have validator controls associated with it. On selecting the dropdown, only the validators specific to the selected value should fire

Here is the ASPX markup that contains the dropdownlist, textbox and validators


<form id="form1" runat="server">
<div>

<asp:DropDownList ID="TypeList" runat="server" OnChange="TypeList_Change(this);">
    <asp:ListItem Value="Name" Selected="True">Name</asp:ListItem>
    <asp:ListItem Value="Date">Date</asp:ListItem>
    <asp:ListItem Value="Phone">Phone</asp:ListItem>
</asp:DropDownList>
</div>
<asp:TextBox ID="ValueText" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="NameReq" runat="server"
     ControlToValidate="ValueText">*</asp:RequiredFieldValidator>
<asp:RequiredFieldValidator ID="DateReq" runat="server" 
     ControlToValidate="ValueText">*</asp:RequiredFieldValidator>
<asp:CompareValidator ID="DateVal" runat="server" ControlToValidate="ValueText"
     Type="Date" Operator="DataTypeCheck">*</asp:CompareValidator>
<asp:CompareValidator ID="PhoneVal" runat="server" ControlToValidate="ValueText"
     Type="Integer"  Operator="DataTypeCheck">*</asp:CompareValidator>
<asp:Button ID="SubmitBtn" runat="server" Text="Submit"/>
</form>


To enable or disable a validator, the javascript ValidatorEnable(val, enable) can be used. The way to find the list of validators for a particular selection is to hard-code the validator IDs in a 2D array. The javascript function for OnChange event handler of the dropdownlist is given below:


<script type="text/javascript" >

var list = [['NameReq'], ['DateReq', 'DateVal'], ['PhoneVal']];

function TypeList_Change(c) {
    for (var i = 0; i < list.length; i++) {
        var valList = list[i];
        var enabled = (i == c.selectedIndex);
        for (var j = 0; j < valList.length; j++) {
            var validator = document.getElementById(valList[j]);
            ValidatorEnable(validator, enabled);
        }
    }
}
    
</script>

When the document is loaded initially or on any postback, the validators have to be enabled appropriately. So add this code to the body onload eventhandler

<body onload="TypeList_Change(document.getElementById('TypeList'));">

Permalink | No Comments | Leave your comment
 

Camel-Casing TextBox Text

In a textbox, the text needs to be displayed as Camel-cased

Camel-case is where the first letter of every word is capitalized. Eg, How Are You? This can be done using the text-transform style as follows:


<asp:TextBox runat="server" style="text-transform: Capitalize;"/>

Permalink | 1 Comment | Leave your comment
 
Commented by Madhanlal JM at 10-Aug-2010 09:14 AM
Nice tweaking..