Navigation

Search

Categories

On this page

Using jQuery to Create an Image Slideshow
Using jQuery to Restrict Textbox Content to Alphabetic Characters
Clicking a Gridview to Get the Cell Contents Using jQuery
Using the jQuery Tablesorter with ASP.NET
Using Cookies With jQuery
jQuery Collapsible Panel
jQuery Photo Plugin
11 Ways to Increase Your jQuery Performance and jQuery Cheatsheet
Search and Highlight a GridView Using jQuery
Using jQuery to Swap Images
jQuery Grid Plugin
Using jQuery to Grab Text and Value of the Selected RadioButton
Calculating Total of Checked Items using jQuery
Making Form Elements Read-Only Using jQuery
Using jQuery to Hide Rows or Columns in a Gridview
Basic jQuery Selectors
Using jQuery to Filter Table Values
JTIP – jQuery Tooltip
Search and Filter Dropdownlist
Highlighting a Selected Checkbox Item
Change or Set HTML Attributes Using jQuery
Changing Stylesheets Using jQuery
Changing Div Content Using jQuery
Microsoft AJAX Content Delivery Network (CDN)
Using jQuery to Hide Table Rows in a Gridview
Naming a jQuery Function
Setting up Visual Studio Intellisense for jQuery
Passing a Value from Javascript to ASP.NET (Client to Server)
jQuery and Checkbox Mania
jQuery: Expanding/Collapsing a Box
jQuery: Check/uncheck all checkboxes with specific value
jQuery Slideshow Cycle Plugin
Using jQuery to Return a Gridview as an AJAX Response
Using jQuery with ASP.NET
jQuery and the Selectbox
Using the jQuery loadData method to load an external file
jQuery User Interface
Using jQuery to Change the Background Color of Rows on Hover
Check/Uncheck all Items in an ASP.NET CheckBox List using jQuery

Archive

Blogroll

Disclaimer
The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.

RSS 2.0 | Atom 1.0 | CDF

Send mail to the author(s) E-mail

Total Posts: 240
This Year: 46
This Month: 3
This Week: 0
Comments: 0

Sign In
Pick a theme:

# Thursday, June 03, 2010
Thursday, June 03, 2010 7:22:31 PM (GMT Daylight Time, UTC+01:00) ( jQuery )


Here is a working demo of this code.

<%@ Page Language="VB" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>jQuery Image Slideshow</title>

<script src="http://code.jquery.com/jquery-1.4.1-vsdoc.js" type="text/javascript"></script>
<script type="text/javascript">
$(function() {
    var imgs = [
    '../images/1.jpg',
    '../images/2.jpg',
    '../images/3.jpg',
    '../images/4.jpg'];
    var cnt = imgs.length;
    var $imageSlide = $('img[id$=imageSlide]');
    // set the image control to the last image
    $imageSlide.attr('src', imgs[cnt - 1]);
    setInterval(Slider, 4000);
    function Slider() {
        $imageSlide.fadeOut("slow", function () {
        $(this).attr('src', imgs[(imgs.length++) % cnt]).fadeIn("slow");
     });
    }
});
</script>

</head>


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

<div class="smallDiv">
<h2>Image Slide Show - Image Changes Every 4 Seconds</h2><br />
<asp:Image ID="imageSlide" runat="server" class="imgdiv" />
</div>

</form>

</body>
</html>
Comments [0] | | # 
Thursday, June 03, 2010 7:11:48 PM (GMT Daylight Time, UTC+01:00) ( jQuery )


Here is a working demo of this example.

<%@ Page Language="VB" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>jQuery Alpha Characters Only</title>


<script src="http://code.jquery.com/jquery-1.4.1-vsdoc.js" type="text/javascript"></script>
<script type="text/javascript">
    $(function () {
        $(".gv input.rate").bind('keyup blur', function (e) {
            if (this.value.match(/[^a-zA-Z ]/g)) {
                this.value = this.value.replace(/[^a-zA-Z ]/g, '');
            }
        });
    });
</script>
</head>

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

<asp:SqlDataSource
        id="srcMovies"
        ConnectionString="<%$ ConnectionStrings:MyDatabase %>"
        SelectCommand="SELECT Id,Title,Director FROM Movies"
        Runat="server" />


        <h3>Using a Gridview</h3>
<div class="tableDiv">
        <asp:GridView
        id="grdMovies"
        DataSourceID="srcMovies"
        DataKeyNames="Id" 
        AutoGenerateColumns="false"
        Runat="server" class="gv">

        <Columns>
        
        <asp:BoundField DataField="Id" HeaderText="Id" />
        <asp:BoundField DataField="Title" HeaderText="Title" />
        <asp:TemplateField HeaderText="Comments">
        <ItemTemplate>
            <asp:TextBox id="txtComments" runat="server" MaxLength="25" class="rate" />
        </ItemTemplate>
        </asp:TemplateField>
        </Columns>
        </asp:GridView>
        <p id="para"></p>
</div>
</form>

</body>
</html>
Comments [0] | | # 
Thursday, June 03, 2010 5:51:24 PM (GMT Daylight Time, UTC+01:00) ( jQuery )


Here is a working demo on how this works.

<%@ Page Language="VB" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">

    Sub grdMovies_PreRender(ByVal sender As Object, ByVal e As EventArgs)
        If grdMovies.Rows.Count > 0 Then
            grdMovies.UseAccessibleHeader = True
            'Adding the <thead> and <tbody> elements   
            grdMovies.HeaderRow.TableSection = TableRowSection.TableHeader
        End If
    End Sub
</script>
    
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>jQuery Gridview Cell Contents</title>

<style type="text/css">
.highlite
{
    background-color:Gray;
}
</style>
<script src="http://code.jquery.com/jquery-1.4.1-vsdoc.js" type="text/javascript"></script>
<script type="text/javascript">
$(function() {
    $(".gv > tbody > tr:not(:has(table, th))")
        .css("cursor", "pointer")
            .click(function(e) {
                $(".gv td").removeClass("highlite");
                var $cell = $(e.target).closest("td");
                $cell.addClass('highlite');
                var $currentCellText = $cell.text();
                var $leftCellText = $cell.prev().text();
                var $rightCellText = $cell.next().text();
                var $colIndex = $cell.parent().children().index($cell);
                var $colName = $cell.closest("table").find('th:eq(' + $colIndex + ')').text();
                $("#para").empty().append("<b>Current Cell Text: </b>"+ $currentCellText + "<br/>")
                .append("<b>Text to Left of Clicked Cell: </b>"+ $leftCellText + "<br/>")
                .append("<b>Text to Right of Clicked Cell: </b>" + $rightCellText + "<br/>")
                .append("<b>Column Name of Clicked Cell: </b>" + $colName)
            });
        });
</script>

</head>


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

<asp:SqlDataSource
        id="srcMovies"
        ConnectionString="<%$ ConnectionStrings:MyDatabase %>"
        SelectCommand="SELECT Id,Title,Director FROM Movies"
        Runat="server" />


        <h3>Using a Gridview</h3>
<div class="tableDiv">
        <asp:GridView
        id="grdMovies"
        DataSourceID="srcMovies"
        DataKeyNames="Id"
        OnPreRender="grdMovies_PreRender"
        Runat="server" class="gv" />

        <p id="para"></p>
</div>
</form>

</body>
</html>

We want to select only those rows which are inside the TBODY:

$(".gv > tbody > tr:not(:has(table, th))") 

We have used ‘e.target’ to find out the element that was clicked. This object is cached in the ‘cell’ variable:

var $cell = $(e.target).closest("td"); 

The closest() as given in the jQuery documentation, “works by first looking at the current element to see if it matches the specified expression, if so it just returns the element itself. If it doesn't match then it will continue to traverse up the document, parent by parent, until an element is found that matches the
specified expression.”

With the help of the ‘cell’ variable, we can use the DOM tree traversal methods like prev() and next(), to retrieve the value of the immediate ‘preceding’ and ‘following’ elements, respectively.

var $leftCellText = $cell.prev().text();
var $rightCellText = $cell.next().text(); 

Similarly the column header text is retrieved using the code shown below.

var $colIndex = $cell.parent().children().index($cell);
var $colName = $cell.closest("table").find('th:eq(' + $colIndex + ')').text(); 

As shown above, after retrieving the column index, we use the closest() method to traverse up the DOM, parent by parent until we find the table element. The Header text is then selected using:

('th:eq(' + $colIndex + ')').text()
Comments [0] | | # 
# Tuesday, June 01, 2010
Tuesday, June 01, 2010 7:16:36 PM (GMT Daylight Time, UTC+01:00) ( jQuery )


Many of the data controls used by ASP.NET support built-in table sorting but they use a lot of resources.  Even using the ASP.NET AJAX controls and UpdatePanels can be a little clumsy. 

A better solution is to use the jQuery plugin tablesorter. Here are a couple of examples on how to use this plugin with both a Gridview and a Listview.

First, here is a working demo of the code below.

<%@ Page Language="VB" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
'By default the gridview does not include the <thead> and <tbody> tags
    Sub grdMovies_PreRender(ByVal sender As Object, ByVal e As EventArgs)
        If grdMovies.Rows.Count > 0 Then
            grdMovies.UseAccessibleHeader = True
            'Adding the <thead> and <tbody> elements   
            grdMovies.HeaderRow.TableSection = TableRowSection.TableHeader
        End If
    End Sub
</script>
    
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>jQuery Table Sorter</title>
<script src="http://code.jquery.com/jquery-1.4.1-vsdoc.js" type="text/javascript"></script>
<script src="jquery/jquery.tablesorter.min.js" type="text/javascript"></script>
<script type="text/javascript">

    $(function () {
        // make the Listview table sortable
        $("#moviesTable").tablesorter();

        // make the Gridview table sortable
        $("#grdMovies").tablesorter();
    });    
    </script> 
</head>


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

<asp:SqlDataSource
        id="srcMovies"
        ConnectionString="<%$ ConnectionStrings:xxxxx %>"
        SelectCommand="SELECT Id,Title,Director FROM Movies"
        Runat="server" />

<h3>Using a Listview</h3>

<asp:ListView ID="lstMovies" DataSourceID="srcMovies" runat="server">
        <LayoutTemplate>
            <table id="moviesTable">
            <thead>
                <tr>
                    <th title="Sort by Id">Id</th>
                    <th title="Sort by Title">Title</th>
                    <th title="Sort by Director">Director</th>                    
                </tr>
            </thead>
            <tbody>
                    <asp:PlaceHolder ID="ItemPlaceholder" runat="server" />
            </tbody>
            </table>
        </LayoutTemplate>
        <ItemTemplate>
            <tr>
                <td><%# Eval("Id") %></td>
                <td><%# Eval("Title")%></td>
                <td><%# Eval("Director")%></td>
            </tr>
        </ItemTemplate>
        </asp:ListView>

        <h3>Using a Gridview</h3>

        <asp:GridView
        id="grdMovies"
        DataSourceID="srcMovies"
        DataKeyNames="Id"
        OnPreRender="grdMovies_PreRender"
        Runat="server" />
</form>

</body>
</html>
Comments [0] | | # 
# Friday, March 19, 2010
Friday, March 19, 2010 6:39:07 PM (GMT Standard Time, UTC+00:00) ( jQuery )


Probably the easiest way to use cookies with jQuery is to use Klaus Hartl’s cookie plugin:

http://www.stilbuero.de/2006/09/17/cookie-plugin-for-jquery/

Here’s an article with examples on how to use it

http://www.shopdev.co.uk/blog/cookies-with-jquery-designing-collapsible-layouts/

Comments [0] | | # 
# Wednesday, March 10, 2010
Wednesday, March 10, 2010 9:21:03 PM (GMT Standard Time, UTC+00:00) ( jQuery )


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-7" />
<title>Untitled Document</title>
<style> 
/*CollapsiblePanel*/ 
.ContainerPanel 
{ 
       width:400px; 
       border:1px; 
       border-color:#1052a0;      
       border-style:double double double double; 
} 
.collapsePanelHeader 
{ 
       width:400px; 
       height:25px; 
       background-image: url(http://www.asp.net/AJAX/AjaxControlToolkit/Samples/images/bg-menu-main.png); 
       background-repeat:repeat-x; 
       color:#FFF; 
       font-weight:bold; 
} 
.HeaderContent 
{ 
       float:left; 
       padding-left:5px;
       font-family:Arial, Helvetica, sans-serif;
       font-size: small;
} 
.Content 
{ 
       
} 
.ArrowExpand 
{ 
       background-image: url(http://www.asp.net/AJAX/AjaxControlToolkit/Samples/images/expand_blue.jpg);
       width:13px; 
       height:13px; 
       float:right; 
       margin-top:7px; 
       margin-right:5px;
       margin-bottom: 5px; 
} 
.ArrowExpand:hover 
{ 
       cursor:hand; 
} 
.ArrowClose 
{ 
       background-image: url(http://www.asp.net/AJAX/AjaxControlToolkit/Samples/images/collapse_blue.jpg); 
       width:13px; 
       height:13px; 
       float:right; 
       margin-top:7px; 
       margin-right:5px;
       margin-bottom: 5px;
} 
.ArrowClose:hover 
{ 
       cursor:hand; 
} 
</style>
<script type="text/javascript" src="http://jqueryjs.googlecode.com/files/jquery-1.3.2.min.js"></script> 
       <script language="javascript"> 
            $(document).ready(function() {
                $("DIV.ContainerPanel > DIV.collapsePanelHeader ").toggle( 
                function() {
                $(this).html( $(this).html().replace("(Show","(Hide") )
                    $(this).next("div.Content").show("slow");
                    $("DIV.ArrowExpand",this).attr("class", "ArrowClose");
                },
                function() {                   
                $(this).html( $(this).html().replace("(Hide","(Show") )
                    $(this).next("div.Content").hide("slow");
                    $("DIV.ArrowClose",this).attr("class", "ArrowExpand");
                });             
            });           
        </script>
</head> 
<body>
<div id="ContainerPanel" class="ContainerPanel">
    <div id="header" class="collapsePanelHeader"> 
        <div id="dvHeaderText" class="HeaderContent">jQuery Collapsible Panel1 (Show Details...)</div> 
        <div id="dvArrow" class="ArrowExpand"></div> 
    </div> 
    <div id="dvContent" class="Content" style="display:none"> 
        /*Content*/ 
    </div> 
</div> 
   
</body>
</html>
Comments [0] | | # 
# Wednesday, February 24, 2010
Wednesday, February 24, 2010 8:39:35 PM (GMT Standard Time, UTC+00:00) ( jQuery )


A jQuery plugin for rendering rich, fast-performing photo galleries

http://www.twospy.com/galleriffic/

Comments [0] | | # 
# Wednesday, January 20, 2010
# Friday, January 15, 2010
Friday, January 15, 2010 9:24:10 PM (GMT Standard Time, UTC+00:00) ( Gridview | jQuery )

 

This cool example allows you to enter some text into a textbox which searches and highlights the results in a Gridview.  Here is a working demo. And another example.

<script type="text/javascript" src="http://ajax.Microsoft.com/ajax/jquery/jquery-1.3.2.js"></script>

    <script type="text/javascript">
        $(function() {
            var $txtBox = $('input[id$=txtSearch]');
            $txtBox.keyup(function(e) {
            searchText();
        });
        
        function searchText() {
            var $txt = $txtBox.val().toLowerCase();
                $(".grid td").removeClass("highlight");
                if ($txt) {
                $(".grid > tbody > tr > td:not(:has(table, tr))")
                .filter(function() {
                return $(this).text().toLowerCase().indexOf($txt) != -1;
                }).addClass('highlight');
                }
            }
            searchText();
        });
</script>
    
</head>
<body>

<form runat="server">
Enter Text Here: <asp:TextBox ID="txtSearch" runat="server" /><br /><br />

<asp:gridview runat="server" CellPadding="4" 
ForeColor="#333333" GridLines="None" 
AllowSorting="false" class="grid" 
id="dgMovies" Width="80%" 
HorizontalAlign="Center" 
Font-Names="Tahoma" 
Font-Size="Small" 
EmptyDataText="No records were found">
    <RowStyle BackColor="#F7F6F3" ForeColor="#333333" />    
    <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
    <HeaderStyle BackColor="gray" Font-Bold="True" ForeColor="Black" />
    <AlternatingRowStyle BackColor="White" ForeColor="#284775" />
</asp:gridview>

</form>
Comments [0] | | # 
Friday, January 15, 2010 8:47:13 PM (GMT Standard Time, UTC+00:00) ( jQuery )


This would be helpful when expanding and collapsing panels.  Here is an example.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title>jQuery from Microsoft AJAX CDN</title>
        <script type="text/javascript" src="http://ajax.Microsoft.com/ajax/jquery/jquery-1.3.2.js"></script>

        <script type="text/javascript">        
        $(function() {
            $('img[id$=imageSwap]').toggle(
                function() {
                $(this).attr("src", "../images/Hide.gif");
            },
                function() {
                $(this).attr("src", "../images/Show.gif");
                }
                );
            });        
        </script>
    </head>
    <body>


    <h2>Click on the image to swap</h2>
    <br /><br />
    <asp:Image ID="imageSwap" runat="server"
    ImageUrl="~/images/Show.gif" />
    
</body>
</html>
Comments [0] | | # 
Friday, January 15, 2010 6:54:08 PM (GMT Standard Time, UTC+00:00) ( ASP.NET | jQuery )


Pretty amazing grid plugin for ASP.NET. He has versions for both ASP.NET and PHP.

http://www.trirand.com/blog/?page_id=5

Comments [0] | | # 
# Tuesday, December 22, 2009
Tuesday, December 22, 2009 3:49:58 PM (GMT Standard Time, UTC+00:00) ( jQuery )


Retrieving the index and value of a radio button is a very common requirement in our applications and
can be easily achieved using jQuery. In this example, we first retrieve the radio buttons using

var $radBtn = $("table.tbl input:radio");

Since this is a RadioButtonList, the control gets rendered as a table. When the user clicks on any of the
radio buttons, we first store the checked radiobuttons in the $radChecked variable to improve selector
performance

var $radChecked = $(':radio:checked');

We then use $radChecked.val() to retrieve the value and $radChecked.next().text() to retrieve the text.
Observe how we are accessing the value of a radiobutton using

$radChecked.next().text().

This is because the RadioButton gets rendered like this:

<td>
<input id="rbl_0" type="radio" name="rbl" value="0" />
<label for="rbl_0">dotnetcurry.com</label>
</td>

To access the value, which is inside the label, we use next() which finds the very next sibling of each
radiobutton, which in our case, is the label control.

Here is a working demo:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Using jQuery to Grab Text and Value of the Selected RadioButton</title>

<script type="text/javascript" src="http://ajax.Microsoft.com/ajax/jquery/jquery-1.3.2.js"></script>

<script type="text/javascript">
$(function() {
    var $radBtn = $("table.tbl input:radio");
        $radBtn.click(function() {
        var $radChecked = $(':radio:checked');
            $("#para").text('')
                .append("<b>Index: </b>" +
                $radChecked.val() + "<br/>")
                .append("<b>Value: </b>" +
                $radChecked.next().text());
        });
});
</script>

</head>
<body>
<form id="form1" runat="server">
<div class="smallDiv">
<h2>Using jQuery to Grab Text and Value of the Selected RadioButton</h2><br />
The movie I like the most is: <br />

<asp:RadioButtonList ID="rbl" runat="server" class="tbl" ToolTip="Select a Radio Button to see its text and value">
    <asp:ListItem Text="Waiting for Guffmam" Value="0"></asp:ListItem>
    <asp:ListItem Text="Borat" Value="1"></asp:ListItem>
    <asp:ListItem Text="Best In Show" Value="2"></asp:ListItem>
</asp:RadioButtonList>

<br />
<p id="para"></p>
</div>
</form>
</body>
</html>
Comments [0] | | # 
Tuesday, December 22, 2009 3:26:24 PM (GMT Standard Time, UTC+00:00) ( jQuery )


Here is a working demo

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Calculating Total of Checked Items using jQuery</title>

<script type="text/javascript" src="http://ajax.Microsoft.com/ajax/jquery/jquery-1.3.2.js"></script>

<script type="text/javascript">
$(function() {
    var total;
    var checked = $('input:checkbox').click(function(e) {
        calculateSum();
});

function calculateSum() {
    var $checked = $(':checkbox:checked');
    total = 0.0;
    $checked.each(function() {
    total += parseFloat($(this).next().text());
    });
    $('#total').text("Your Total Amount Is: " + total.toFixed(2));
}
});
</script>
</head>

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

<h2>Click on the checkboxes to add up the totals</h2>
    Choose the items you want to buy: <br />
<table>
<tr>
    <td>Apples</td>
    <td><asp:CheckBox ID="cb1" runat="server" Text="5.23" /></td>
</tr>

<tr>
    <td>Bananas</td>
    <td><asp:CheckBox ID="cb2" runat="server" Text="2.20" />
    </td>
</tr>
<tr>
    <td>Strawberries</td>
    <td><asp:CheckBox ID="cb3" runat="server" Text="8.54" />
    </td>
</tr>
<tr>
    <td>Pineapples</td>
    <td><asp:CheckBox ID="cb4" runat="server" Text="15.14" /></td>
</tr>
</table>
<br />
    <p id="total"></p>

</form>
</body>
</html>
Observe how we are accessing the value of a checkbox using $(this).next().text());
This is because the checkbox gets rendered like this:

<td>
<input id="Checkbox1" type="checkbox" name="cb1" />
<label for="cb1">5.23</label>
</td>

To access the value, which is inside the label, we use next() which finds the very next sibling of each
checkbox, which in our case is the label control. The parseFloat( ) parses strings into numbers.
The result is displayed in a paragraph (total) using the toFixed() method, which rounds the result to the
specified number of decimal places, in our case 2.

$('#total').text("Your Total Amount Is: " + total.toFixed(2));
Comments [0] | | # 
# Monday, December 21, 2009
Monday, December 21, 2009 6:54:44 PM (GMT Standard Time, UTC+00:00) ( jQuery )
 
This example will make textboxes that do not contain any text read-only at run-time. Textboxes 1 and 3 will be read-only 
while 2 and 4 can be edited.
<script type="text/javascript">
   $(function() {
      $('input:text[value!=]').each(function() {
      $(this).attr('readonly', true);
     });
});
</script>
<asp:TextBox ID="txt1" runat="server" Text="ReadOnly"/><br />
<asp:TextBox ID="txt2" runat="server" Text=""/><br />
<asp:TextBox ID="txt3" runat="server" Text=""/><br />
<asp:TextBox ID="txt4" runat="server" Text="ReadOnly" />
 
Comments [0] | | # 
# Friday, December 18, 2009
Friday, December 18, 2009 3:02:10 AM (GMT Standard Time, UTC+00:00) ( Gridview | jQuery )


This is a neat example of how to click on rows in a Gridview to highlight them and click on a keyboard letter to hide/remove the selected rows.

Here is a working demo

 

<%@ Page Language="VB" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
    <style type="text/css">
     .highlite {
        background-color: Yellow;
    }
    
    .tableDiv {
    background-color:White;
    font-family: "Lucida Grande", Verdana, Arial; 
    font-size:13px; 
    color:#000000;
    width:460px; 
    margin-left:auto;
    margin-right:auto;
    padding:10px;
    border:solid 1px #c6cfe1;
}

    </style>

    <title>Format Grid</title>
  <script src="http://ajax.Microsoft.com/ajax/jquery/jquery-1.3.2.js" type="text/javascript"></script>

    <script type="text/javascript">
        $(function() {
            $(".grid > tbody > tr:not(:has(table, th))")
                .css("cursor", "pointer")
                    .click(function() {
                        $(this).toggleClass('highlite');
                });
            $(document).keyup(function(e) {
                var key = (e.keyCode ? e.keyCode : e.charCode);
                if (key == 68) { // D OR d
                    var cnt = $("tr.highlite").length;
                    $("tr.highlite").remove();
                    $("#message")
                        .html("<b>" + cnt + "</b>" + " row(s) hidden");
                }
            });
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
    
    <div class="tableDiv">
    <h4>Click on the Rows to Highlight them. Press 'd' or 'D' to Remove the Rows</h4><br />
<p id="message"></p>
   
    <asp:GridView
        id="grdMovies"
        DataSourceID="srcMovies"
        GridLines="None" class="grid"        
        Runat="server" CellPadding="4" ForeColor="#333333" >        
        </asp:GridView>
    
    <asp:SqlDataSource
        id="srcMovies"
        ConnectionString="<%$ ConnectionStrings:MyDatabase %>"
        SelectCommand="SELECT Id,Title,Director FROM Movies"
        Runat="server" />
    
    </div>
    </form>
</body>
</html>

To highlight and remove columns, the code isn’t that much different from the code above. See this working demo on how to highlight and remove columns in a gridview.

<script type="text/javascript">
        $(function() {
            $(".grid th")
                .css("cursor", "pointer")
                    .click(function(e) {
                         var $idx = $(this).parent().children().index($(this));
                        $(".grid th:eq(" + $idx + "),.grid tr td:nth-child(" + ($idx + 1) + ")")
                            .toggleClass("highlite");
                    });
                
            $(document).keyup(function(event) {
                var key = event.keyCode || event.charCode || 0;
                if (key == 68) { // D OR d
                    var cnt = $("th.highlite").length;
                    $("td.highlite, th.highlite").remove();
                    $("#message")
                    .html("<b>" + cnt + "</b>" + " column(s) deleted!!");
                }
            });
        });
</script>
Comments [0] | | # 
# Friday, December 11, 2009
Friday, December 11, 2009 7:42:41 PM (GMT Standard Time, UTC+00:00) ( jQuery )

 

I always get these jQuery selectors confused in jQuery so I’m posting them mostly for my own reference

Selector CSS jQuery Description
Tag name P $(‘p’) Selects all paragraphs
ID #someID $(‘#someID’) Selects the single element in the document that has an ID with this
Class .someclass $(‘.someclass’) Selects all elements in the document that have a class of some class
Comments [0] | | # 
# Monday, December 07, 2009
Monday, December 07, 2009 1:34:17 AM (GMT Standard Time, UTC+00:00) ( jQuery )


<script type="text/javascript"
  src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
  // hide rows that do not mention ‘Eric’ in the 1st column
  $('#tickets>tr>td:nth-child(1)')
    .not(':contains("Eric")')
    .parent()
    .hide();
});
</script>

<table id="tickets">
  <tr>
    <th scope="col">Ticket</th>
    <th scope="col">Entered by</th>
    <th scope="col">Assigned to</th>
  </tr>
  <tr>
    <td>Pick fantasy pinball team</td>
    <td>Eric</td>
    <td>Eric</td>
  </tr>
  <tr>
    <td>Buy lunch</td>
    <td>Eric</td>
    <td>John</td>
  </tr>
  <tr>
    <td>Write blog post</td>
    <td>Eric</td>
    <td>John</td>
  </tr>
  <tr>
    <td>Make tea</td>
    <td>John</td>
    <td>Eric</td>
  </tr>
  <tr>
    <td>Get biscuits for CFUG</td>
    <td>Andy</td>
    <td>Andy</td>
  </tr>
  <tr>
    <td>Add task filtering</td>
    <td>Simon</td>
    <td>John</td>
  </tr>
  <tr>
    <td>Style tasks table</td>
    <td>Simon</td>
    <td>Andy</td>
  </tr>
  <tr>
    <td>Schedule meeting</td>
    <td>Eric</td>
    <td>Simon</td>
  </tr>
</table>

Comments [0] | | # 
# Friday, December 04, 2009
Friday, December 04, 2009 4:34:59 PM (GMT Standard Time, UTC+00:00) ( jQuery )


I was looking around for an AJAX style tooltip and found this one to be the best for my needs.

Here are some examples:

http://www.eduteka.org/ajax/qtips/

http://codylindley.com/Javascript/264/jtip-a-jquery-tool-tip

Here’s a basic summary of the code needed to get it up and running.

First you’ll need the actual jTip plugin and associated stylesheet and images which can be downloaded here.

This is an example of the javascript needed to call the tooltip

<script type="text/javascript">
// this shows the preview rollover    
  $( domReady );  
  function domReady() { 
    $(".Id_Field").click( openWindow ) 
  }
    
  function openWindow() {
      strIdValue = $(this).val();
      JT_show('field.details.preview.aspx'+strIdValue, 'name', 'myLink');
  }      
</script>
Finally, here is an example of an ItemTemplate in a Gridview. The magic happens because of the class=”jTip”.
<asp:templatefield ShowHeader="true" ItemStyle-HorizontalAlign="Center" HeaderText="Preview" HeaderStyle-Font-Size="Small">
<itemtemplate>            
<a href="field.details.preview.aspx?id_field=<%# Container.DataItem("id_field") %>" class="jTip" id="<%# Container.DataItem("id_field") %>" 
name="<%# Container.DataItem("FieldName") %>"><img src="../images/preview.png" alt="Preview Field" border="0" /></a> </itemtemplate> </asp:templatefield>
Comments [0] | | # 
# Monday, November 09, 2009
Monday, November 09, 2009 5:31:41 PM (GMT Standard Time, UTC+00:00) ( jQuery )


This is probably one of my all-time favorite jQuery examples.  Here is a working demo.

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Search and Filter a DropDownList</title>
    <script src="http://ajax.Microsoft.com/ajax/jquery/jquery-1.3.2.js" type="text/javascript"></script>
    
    <script type="text/javascript">
        $(function() {
            var $txt = $('input[id$=txtBox1]');
            var $ddl = $('select[id$=ddlCarModels]');
            var $items = $('select[id$=ddlCarModels] option');
 
            $txt.keyup(function() {
                searchDdl($txt.val());
            });
 
            function searchDdl(item) {
                $ddl.empty();
                var exp = new RegExp(item, "i");
                var arr = $.grep($items,
                    function(n) {
                        return exp.test($(n).text());
                    });
 
                if (arr.length > 0) {
                    countItemsFound(arr.length);
                    $.each(arr, function() {
                        $ddl.append(this);
                        $ddl.get(0).selectedIndex = 0;
                    }
                    );
                }
                else {
                    countItemsFound(arr.length);
                    $ddl.append("<option>No Items Found</option>");
                }
            }
 
            function countItemsFound(num) {
                $("#results").empty();
                if ($txt.val().length) {
                    $("#results").html(num + " items found");
                } 
            }
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <h2>Enter Text in the TextBox to Filter the DropDownList </h2>
        <br />
        Search Toyota models:<br />
        <asp:TextBox ID="txtBox1" runat="server" ToolTip="Enter Text Here"></asp:TextBox><br />
        <asp:DropDownList ID="ddlCarModels" runat="server" >
            <asp:ListItem Text="Tercel" Value="1"></asp:ListItem>
            <asp:ListItem Text="Camry" Value="2"></asp:ListItem>
            <asp:ListItem Text="Sienna" Value="3"></asp:ListItem>
            <asp:ListItem Text="Corolla" Value="4"></asp:ListItem>
            <asp:ListItem Text="Lexus" Value="5"></asp:ListItem>
            <asp:ListItem Text="Tundra" Value="6"></asp:ListItem>
            <asp:ListItem Text="Yaris" Value="7"></asp:ListItem>
            <asp:ListItem Text="Tacoma" Value="8"></asp:ListItem>
            <asp:ListItem Text="RAV4" Value="9"></asp:ListItem>
            <asp:ListItem Text="Highlander" Value="10"></asp:ListItem>
            <asp:ListItem Text="Land Cruiser" Value="11"></asp:ListItem>
            <asp:ListItem Text="Venza" Value="12"></asp:ListItem>
        </asp:DropDownList>
        <br />
        <p id="results"></p>
        <br /><br />
        Tip: Items get filtered as characters are entered in the textbox.
        Search is not case-sensitive
    </div>
 
    </form>
</body>
</html>
Comments [0] | | # 
# Thursday, October 15, 2009
Thursday, October 15, 2009 9:23:55 PM (GMT Daylight Time, UTC+01:00) ( jQuery )


Remember that a CheckBoxList is rendered as a table in the browser.   To find each item, we need to look in the <table> tag for each item. But the text for each item is rendered in a <label> tag.

Here is a working demo.

<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
    <title>Highlight A Selected CheckBox Item</title>
    <script language="javascript" type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery/jquery-1.3.2.min.js"></script>
    <script type="text/javascript" language="javascript">
        $(document).ready(function() {
            $("table[id$=MyCheckboxList] input").click(function() {
                if ($(this).next().is(".selected")) {
                    $(this).next().removeClass("selected").addClass("notselected");
                }
                else {
                    $(this).next().removeClass("notselected").addClass("selected")
                }
            });          
        });
    </script>
    <style type="text/css">
        .selected
        {
            background-color:Green;
        }
        .notselected
        {
            background-color:White;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">   
        <asp:CheckBoxList ID="MyCheckboxList" runat="server">
            <asp:ListItem Text="vanilla"></asp:ListItem>
            <asp:ListItem Text="chocolate"></asp:ListItem>
            <asp:ListItem Text="strawberry"></asp:ListItem>
        </asp:CheckBoxList> 
    </form>
</body>
</html>

In the code above, use the following\jQuery selector to find the CheckBoxList items:

$("table[id$=MyBoxList] input")
Comments [0] | | # 
# Monday, September 21, 2009
Monday, September 21, 2009 9:25:33 PM (GMT Daylight Time, UTC+01:00) ( jQuery )


It’s often necessary to change the HTML attributes of an element dynamically.  This example changes the photo image, alt tag and border width when the link is clicked.  Notice how the properties can be chained together.

Here is a working demo

<html> 
  <head> 
    <title></title> 
    <script type="text/javascript" src="http://ajax.Microsoft.com/ajax/jquery/jquery-1.3.2.js"></script>
    
<script type="text/javascript"> 
  $( domReady );  
  function domReady() { 
    $("#clickMe").click( changeImage ) 
  }
    
  function changeImage() {
      $("#myimage").attr({src : "moe.jpg"}).attr({alt : "Moe Bush"}).attr({border : "10px"});
  }      
    
</script>
   
  </head> 
  <body> 
    
    <a id="clickMe" href="#">Change the image below</a> 
    <br /> 
    <img id="myimage" src="/images/code.for.jpg" alt="code for food" border="0" />

 </body> 
</html>
Comments [0] | | # 
Monday, September 21, 2009 8:58:02 PM (GMT Daylight Time, UTC+01:00) ( jQuery )


This example shows you how to allow your users to change the default stylesheet using jQuery.

Here is a working demo.

Assume you have your default stylesheet:

<link rel="stylesheet" href="plain.css" type="text/css">

List of available stylesheet options:

<ul> 
  <li><a id="css-plain" href="#plain">Plain</a></li> 
  <li><a id="css-jazzy" href="#jazzy">Jazzy</a></li> 
  <li><a id="css-disco" href="#disco">Disco</a></li> 
</ul>

The jQuery which actually changes the stylesheet:

<script type="text/javascript"> 
  $( domReady ); 
  
  function domReady() { 
    // plain 
    $("#css-plain").click(function() { 
      $("link[rel=stylesheet]").attr({href : "/css/plain.css"}); 
    }); 
 
    // jazzy
    $("#css-jazzy").click(function() { 
      $("link[rel=stylesheet]").attr({href : "/css/jazzy.css"}); 
    }); 
 
    // disco 
    $("#css-disco").click(function() { 
      $("link[rel=stylesheet]").attr({href : "/css/disco.css"}); 
    }); 
  }; 
</script>
Comments [0] | | # 
Monday, September 21, 2009 8:28:43 PM (GMT Daylight Time, UTC+01:00) ( jQuery )


Here is a working demo of this code

<html> 
  <head> 
    <title></title> 
    <script type="text/javascript" src="http://ajax.Microsoft.com/ajax/jquery/jquery-1.3.2.js"></script> 
    
    <script type="text/javascript">        
        $( domReady );        
        function domReady() {
            $('#btn').click( showMessage );
        }
        
        function showMessage() {
            $('#message').html("<h2>Goodbye from jQuery!</h2>");
        }        
        </script> 
   
  </head> 
  <body> 
    <button id="btn">Change Content</button>

    <div id="message">
        <h2>Hello from jQuery!</h2>
    </div>    
    
  </body> 
</html>
 
Comments [0] | | # 
# Thursday, September 17, 2009
Thursday, September 17, 2009 4:03:55 PM (GMT Daylight Time, UTC+01:00) ( ASP.NET AJAX | Javascript/AJAX | jQuery )


http://www.asp.net/ajax/CDN/

Here is a working demo of this code example

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title>jQuery from Microsoft AJAX CDN</title>
        <script src="http://ajax.Microsoft.com/ajax/jquery/jquery-1.3.2.js" type="text/javascript"></script>

        <script type="text/javascript">
        
        $( domReady );
        
        function domReady() {
            $('#btn').click( showMessage );
        }
        
        function showMessage() {
            $('#message').fadeIn('slow');
        }
        
        </script>
    </head>
    <body>

    <button id="btn">Show Message</button>

    <div id="message" style="display:none">

        <h1>Hello from jQuery!</h1>

    </div>

    </body>
    </html>

 
 
 
Comments [0] | | # 
# Wednesday, September 09, 2009
Wednesday, September 09, 2009 4:26:55 PM (GMT Daylight Time, UTC+01:00) ( CSS | Gridview | jQuery )

 

I’m working on a project which requires users to have the ability to hide rows in a table associated with a certain value.  I checked around and using jQuery seemed to be the best option.   This is a much more elegant approach than doing it server-side.  Here’s what I did.

First, I included a hidden field as a row in my Gridview.  This field is a bit field (true/false) which two CSS classes and one of which is ‘hiddenField’ which makes the field invisible to the user.

<asp:boundfield DataField="InternalOnly" ShowHeader="true" ItemStyle-CssClass="hiddenField internalField" />

CSS code:

.hiddenField {    
    visibility:hidden;
}

Above the Gridview, I included a checkbox with an Id of chkInternal which the user can toggle to hide/show the rows in the Gridview

<input name="chkInternal" id="chkInternal" type="checkbox" />Exclude Non-product fields

Lastly, I use this bit of jQuery code to hide/show the rows in the table. When the chkInternal checkbox is checked, it applies the CSS property display: none to the the entire table row using the jQuery method .parent. It looks for the second CSS class property ‘internalField’. Conversely, when the checkbox chkInternal is not checked, the CSS property display: block is applied to the row making the row visible again. 

<script language="javascript" type="text/javascript">    
$(document).ready(function() {      
      $('#chkInternal').click(
          function() {
          $('.internalField').each(function() {
             if ($("#chkInternal").is(":checked"))
            {
                if ($(this).text() == "True") 
                        $(this).parent().css('display', 'none');                
            }
            else
            {      
                $(this).parent().css('display', 'block');                
            }
        });                 
    });                      
});
</script>
Comments [0] | | # 
# Wednesday, July 22, 2009
Wednesday, July 22, 2009 9:24:15 PM (GMT Daylight Time, UTC+01:00) ( jQuery )


I looked all over the place for an example of how to name a jQuery function and couldn’t find one.  This is all that really needs to be done.

<script language="javascript" type="text/javascript"> 
    function getDirectorIds() { 
    // code here
} // this gets all of the director id_individual values $(document).ready(function() { getDirectorIds(); }); </script>
Comments [0] | | # 
# Thursday, July 16, 2009
Thursday, July 16, 2009 8:07:18 PM (GMT Daylight Time, UTC+01:00) ( jQuery )


The Learning jquery site has a nice article on how to do this.

Comments [0] | | # 
# Wednesday, July 15, 2009
Wednesday, July 15, 2009 7:18:07 PM (GMT Daylight Time, UTC+01:00) ( Javascript/AJAX | jQuery )


This comes up a lot for me when I need to juggle client side and server side values back and forth.  In this example, I will create and set the values on the client side using javascript and then demonstrate how to read those values on the server side using ASP.NET.  To do this we need to follow these steps:

  • Create a HTML hidden field on the page
  • Set the value(s) using javascript
  • Read those values on the server side

The first thing I did was create a repeater control and within the ItemTemplate place a checkbox which contains the value we’re interested in – in this case id_individual.  Notice that the checkboxes have a class value of “DirectorName” which we’ll use in our jQuery next. Next to the checkbox we list the person’s name in label controls. 

<asp:Repeater id="rptDirectors" DataSourceID="dsDirectors" Runat="Server">  
  <ItemTemplate>
      <input type="checkbox" value='<%# Container.DataItem("id_individual") %>' id="chkDirectorName" name="chkDirectorName" runat="Server" class="DirectorName" checked />
      <asp:Label ID="Label1" Text='<%# Eval("DirFName") %>' Runat="Server"/>  <asp:Label ID="Label2" Text='<%# Eval("DirLName") %>' Runat="Server"/><br />      
   </ItemTemplate> 
</asp:Repeater>    

We also need our hidden client-side field which will hold our id_individual values. Notice that it has a runat=”server” property.  This is what makes it accessible to both the client and server sides of this equation. We will also create a asp:Literal control which will show us the value on the server side after the value has been passed to the server side.

<input id="lblCheckedDirs" name="lblCheckedDirs" type="Hidden" runat="server" visible="true" />

<asp:Literal ID="lblServerSideValue" runat="server" Visible="true" />

Next, we will create a javascript function named getDirectorIDs to get the value of each checked checkbox inside of the repeater control rptDirectors.  Using the jQuery library makes it very easy to iterate over the checkboxes to get these values.  We place the comma delimited values into a variable named result. We then place the value of result into the hidden control, lblCheckedDirs.  

<script language="Javascript" type="text/javascript">
    // this gets all of the director id_individual values
    $(document).ready(function getDirectorIDs() {    
        var result = "";
        $(".DirectorName:checked").each(function() {
            result = result + $(this).val() + ",";
        });
        // place the selected id_individual values in the label control lblCheckedDirs
        document.getElementById('lblCheckedDirs').value = result;
    }); 
</script>

Next, our submit button calls both the client side function getDirectorIDs() as well as our server side function btnContinue_Click.  getDirectorIDs populates the client-side hidden control, lblCheckedDirs, and btnContinue_Click populates the server literal control, lblServerSideValue.

<asp:Button ID="btnContinue" runat="server" Text="Continue >>" OnClientClick="getDirectorIDs();" onclick="btnContinue_Click" />    
<script runat="server">
    Protected Sub btnContinue_Click(ByVal sender As Object, ByVal e As System.EventArgs)
        lblServerSideValue.Text = lblCheckedDirs.Value
    End Sub
</script>

Here is the source code for the whole page. 

Comments [0] | | # 
Wednesday, July 15, 2009 4:32:31 PM (GMT Daylight Time, UTC+01:00) ( jQuery )


I’m a relative beginner with jQuery and just starting out with a lot of things but here are some examples on using checkboxes in your applications.

This example checks/unchecks all of the checkboxes on a page.  Clicking on the checkbox with an id of ‘chkAll’ checks/unchecks every checkbox element on the page.

$(document).ready(function() {            
            $('#chkAll').click(
             function() {                
                $("INPUT[type='checkbox']").attr('checked', $('#chkAll').is(':checked'));
            });     
     });
<input name="chkAll" id="chkAll" type="checkbox" Checked />
 

The next example is a little more targeted and is actually the preferred method of doing this.  Rather than targeting every checkbox element on the page, in most cases you will want to target specific checkboxes or form elements.  This case whenever the checkbox with an id of chkDivDirectors is checked, every checkbox element with of class of chkDirector will be checked/unchecked.

$(document).ready(function() {
    $("#chkDivDirectors").click(
        function() {
                $(".chkDirector").attr('checked', $('#chkDivDirectors').is(':checked'));
                           
            });
        });   
<input name="chkDivDirectors" id="chkDivDirectors" type="checkbox" Checked />
<input type="checkbox" id="chkDirectorName" name="chkDirectorName" runat="Server" class="chkDirector" checked />

A slightly different version of this but less preferred method is to look at the element’s id rather than it’s class name. In this example, every checkbox that has an id that begins with ‘chkDirector’ gets checked/unchecked.

$(document).ready(function() {
    $("#chkDivDirectors").click(
        function() {
                $("INPUT[id^='chkDirector']").attr('checked', $('#chkDivDirectors').is(':checked'));                            
            });
        }); 
Comments [0] | | # 
# Wednesday, July 01, 2009
Wednesday, July 01, 2009 8:16:27 PM (GMT Daylight Time, UTC+01:00) ( jQuery )


The show/hide or expand collapse effect is pretty simple with jQuery but I’m stupid so I need to document it here

CSS
#box {
display: none;
}

<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(function()
{

$("#trigger").click(function(event) {
event.preventDefault();
$("#box").slideToggle();
});

$("#box a").click(function(event) {
event.preventDefault();
$("#box").slideUp();
});
});
</script>


<a href="#" id="trigger">TRIGGER</a>

<div id="box">
<a href="#" class="close">[x]</a>
My content here
</div>
Comments [0] | | # 
# Tuesday, June 30, 2009
Tuesday, June 30, 2009 6:02:23 PM (GMT Daylight Time, UTC+01:00) ( jQuery )

I was working on something that required to me to check all checkboxes in a form.  It’s pretty easy to toggle back and forth using jQuery using something like this:

<script type="text/javascript">
    // main check all checkbox
    $(document).ready(function() {            
            $('#chkAll').click(
             function() {                
                $("INPUT[type='checkbox']").attr('checked', $('#chkAll').is(':checked'));
            });     
         });
</script>
<form method="post" action="">
<input name="chkAll" id="chkAll" type="checkbox" />
<input type="checkbox" name="a" value="1" id="" />
<input type="checkbox" name="b" value="2" id="" />
<input type="checkbox" name="c" value="3" id="" />
<input type="checkbox" name="d" value="4" id="" />
<input type="checkbox" name="e" value="5" id="" />
<input type="checkbox" name="f" value="5" id="" />
</form>

However, I also needed something where I wanted checkboxes checked only when their values equaled something specific.  In this case, only checkboxes with a value of 9 will get checked.

<script language="Javascript" type="text/javascript">
$(document).ready(function() {
   $("#chkAll").click(function(event){
      $('input[@type=checkbox]').each( function() {
        if($(this).val()==5)
          this.checked = !this.checked;
      });
   });
});
</script> 

<form method="post" action="">
<input name="chkAll" id="chkAll" type="checkbox" />
<input type="checkbox" name="a" value="1" id="" />
<input type="checkbox" name="b" value="2" id="" />
<input type="checkbox" name="c" value="3" id="" />
<input type="checkbox" name="d" value="4" id="" />
<input type="checkbox" name="e" value="9" id="" />
<input type="checkbox" name="f" value="9" id="" />
</form>

You could also do something like where only checkboxes with an id that begins with “chkEvent” get checked using the “BeginsWith” function ^.

<script language="Javascript" type="text/javascript">
    $(document).ready(function() {
    $("#chkAll").click(
        function() {
                $("INPUT[id^='chkEvent']").attr('checked', $('#chkAll').is(':checked'));
            });
        });   
</script> 




<form method="post" action="">
<input name="chkAll" id="chkAll" type="checkbox" />
<input type="checkbox" name="a" value="1" id="chkEventA" />
<input type="checkbox" name="b" value="2" id="chkEventB" />
<input type="checkbox" name="c" value="3" id="chkEventC" />
<input type="checkbox" name="d" value="4" id="chkEventD" />
<input type="checkbox" name="e" value="9" id="chkEventE" />
<input type="checkbox" name="f" value="9" id="chkEventF" />
</form>
Comments [0] | | # 
# Tuesday, May 19, 2009
Tuesday, May 19, 2009 8:21:02 PM (GMT Daylight Time, UTC+01:00) ( jQuery )


The number of plugins for jQuery popping up all over has been great. If you’re thinking of doing a specific task with jQuery, chances are there’s already a plugin for it.

The jQuery Slideshow Cycle plugin offers an interesting way to display a series of photos. This plugin makes it very easy to display a group of photos similar to a slideshow.

Here is my working example and source code.  I’ve added the ability to select what effect to apply to the pictures through a selectbox.

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>jQuery Picture Cycler</title>
<script type="text/javascript" src="jquery/jquery-1.2.6.min.js"></script>
<script type="text/javascript" src="jquery/jquery.cycle.all.min.js"></script>

<script type="text/javascript">

function pageLoad() {
    getEffect('cover');
}

function ddlEffect_onChange() {
    var effect = document.getElementById("ddlEffect"); 
    var selText = effect.options[effect.selectedIndex].text;
    getEffect(selText);
}

$(document).ready(function getEffect(selText){
    $('#myslides').cycle({
        fx: selText,
        speed: 500,
        timeout: 2000
    });
});

</script>

<style type="text/css">

#myslides {
    width: 370px;
    height: 220px;
    padding: 0;
    margin:  0 auto;
} 

#myslides img {
    padding: 10px;
    border:  1px solid rgb(100,100,100);
    background-color: rgb(230,230,230);
    width: 350px;
    height: 200px;
    top:  0;
    left: 0
}
</style> 
</head>

<body onload="pageLoad();">

Select an effect type:<br/>
 <select name="ddlEffect" id="ddlEffect" onchange="ddlEffect_onChange();">
                <option value="blindX" selected>blindX</option>
                <option value="blindY">blindY</option>
                <option value="blindZ">blindZ</option>
                <option value="cover">cover</option>
                <option value="curtainX">curtainX</option>
                <option value="curtainY">curtainY</option>
                <option value="fade">fade</option>
                <option value="fadeZoom">fadeZoom</option>
                <option value="growX">growX</option>
                <option value="growY">growY</option>
                <option value="scrollUp">scrollUp</option>
                <option value="scrollDown">scrollDown</option>
                <option value="scrollLeft">scrollLeft</option>
                <option value="scrollRight">scrollRight</option>
</select>
 <br/>
<div id="myslides">
 <img src="/images/capitol.jpg" width="350" height="200" />
 <img src="/images/flowers.jpg" width="350" height="200" />
 <img src="/images/countryscene.jpg" width="350" height="200" /> 
</div>

</body>
</html>
Comments [0] | | # 
Tuesday, May 19, 2009 4:28:35 PM (GMT Daylight Time, UTC+01:00) ( jQuery )


This is a cool example of how to return the results of a search formatted as a Gridview using the jQuery ajaxForm method.

Here is a working example

>> jquery.contact.form.response.aspx

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>jQuery Form</title>
<script type="text/javascript" src="jquery/jquery-1.2.6.min.js"></script>
<script type="text/javascript" src="jquery/jquery.form.js"></script>


<script type="text/javascript">

// prepare the form when the DOM is ready 
$(document).ready(function() { 
    // bind form using ajaxForm 
    $('#htmlForm').ajaxForm({ 
        // target identifies the element(s) to update with the server response 
        target: '#htmlExampleTarget', 
 
        // success identifies the function to invoke when the server response 
        // has been received; here we apply a fade-in effect to the new content 
        success: function() { 
            $('#htmlExampleTarget').fadeIn('5000'); 
        } 
    }); 
});

</script>
</head>

<body>
<form id="htmlForm" action="jquery.contact.form.response.gridview.aspx" method="post"> 
    Movie Search: <input type="text" name="title" value="Truth" /> 
    <input type="submit" value="Search Movies" /> 
</form>
Suggestions: "truth","attack","an","space"<br /><br />

<div id="htmlExampleTarget"></div>

</body>
</html>

>> jquery.contact.form.response.gridview.aspx

<%@ Page Language="VB" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>

<script runat="server">
    Sub Page_Load()

        If Not Page.IsPostBack Then
            Dim strTitle As String = Request("title")
            lblTitle.Text = strTitle
        
            BindGridView(strTitle, "Title")
        End If

    End Sub
    
    Sub BindGridView(ByVal strTitle As String, ByVal strSortOrder As String)
        
        Dim con As New SqlConnection(ConfigurationManager.ConnectionStrings("MyDatabase").ConnectionString)
        Dim strSqlText As String = "SELECT Title, Director FROM Movies WHERE Title LIKE '%" & strTitle & "%' ORDER BY " & strSortOrder

        Dim cmd As New SqlCommand(strSqlText)
        con.Open()
        cmd.Connection = con

        dgMovies.DataSource = cmd.ExecuteReader(CommandBehavior.CloseConnection)
        dgMovies.DataBind()

        con.Close()
        con.Dispose()
        
    End Sub
    
    Sub SortGridView(ByVal Sender As Object, ByVal e As GridViewSortEventArgs)
        BindGridView(lblTitle.Text, e.SortExpression.ToString())
    End Sub
       
</script>

<html>
<head><title></title>
</head>
<body>

<form runat="server">

<asp:gridview runat="server" CellPadding="4" 
ForeColor="#333333" GridLines="None" 
AllowSorting="true" OnSorting="SortGridView"
id="dgMovies" Width="80%" 
HorizontalAlign="Center" 
Font-Names="Tahoma" 
Font-Size="Small" 
EmptyDataText="No records were found">
    <RowStyle BackColor="#F7F6F3" ForeColor="#333333" />    
    <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
    <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
    <AlternatingRowStyle BackColor="White" ForeColor="#284775" />
</asp:gridview>

<asp:Label ID="lblTitle" runat="server" Visible="false" />

</form>

</body>
</html>
Comments [0] | | # 
Tuesday, May 19, 2009 4:11:42 PM (GMT Daylight Time, UTC+01:00) ( jQuery )


Visual Studio 2008 SP1 and Visual Web Developer Express SP1 now support intellisense for jQuery. 

Assuming you have installed the hotfix , downloaded the jQuery library and the jQuery VS 2008 IntelliSense documentation, follow these steps to move ahead.

Open Visual Studio 2008 > File > New > Website > Choose ‘ASP.NET 3.5 website’ from the templates > Choose your language (C# or VB) > Enter the location > Ok. In the Solution Explorer, right click your project > New Folder > rename the folder as ‘Scripts’.

Right click the Scripts folder > Add Existing Item > Browse to the path where you downloaded the jQuery library (jquery-1.3.2.js) and the intellisense documentation (jquery-1.3.2-vsdoc.js) > Select the files and click Add.

Here is a working example of the code below.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<%@ Page Language="VB" %>
<html dir="ltr" xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252" />
<title>Learning jQuery</title>

<script type="text/javascript" src="jquery/jquery-1.3.min.js"></script>
<script type="text/javascript" src="jquery/jquery-1.3.2-vsdoc2.js"></script>

<style type="text/css">
        div { 
        background-color:#D5EDEF; 
        color:#4f6b72;
        width:50px; 
        border: 1px solid #C1DAD7; 
 
      }
</style>
 
<script type="text/javascript">
        $(document).ready(function() {
            $("#Button1").click(function() {
                alert("Hello world!");
            }); 
            
            $("#btnAnimate").click(function() {
             $("#Panel1").animate(
            {
                width: "350px",
                opacity: 0.5,
                fontSize: "16px"
            }, 1800);
         });
        });
</script>
    
</head>

<body>

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

<asp:Button runat="server" Text="Button" id="Button1" /><br /><br />

<input id="btnAnimate" type="button" value="Animate" />
<asp:Panel ID="Panel1" runat="server">
        Some sample text in this panel        
</asp:Panel>
        
</form>

</body>

</html>
Comments [0] | | # 
# Friday, March 27, 2009
Friday, March 27, 2009 3:44:44 PM (GMT Standard Time, UTC+00:00) ( jQuery )


I’m not a jQuery or javascript expert so there may be better ways of doing this but here are a few approaches to common tasks involving a selectbox including how to add an option item, remove and option item and display the selected value.

I first start every jQuery function with the document.ready function

<head>
    <title>jQuery and the Selectbox</title>
    <script src="jquery-1.2.6.min.js" type="text/javascript"></script>
   
    <script type="text/javascript">
    
    $(document).ready(function()
      {   
          
      }
    );    
    </script> 
</head>


Then build on this basic structure:

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>jQuery and the Selectbox</title>
    <script src="jquery-1.2.6.min.js" type="text/javascript"></script>
   
    <script type="text/javascript">
    
    $(document).ready(function()
      {   
          $("#myselect").change(onSelectChange);     
      }
    );
    
    function onSelectChange(){   
        // remove the option with a value of option1
        $('#myselect option[value="option1"]').remove();
        
        // add an item to it         
        $("#myselect").append('<option value="option5">option 5</option>'); 
        
        // remove all items
        //$('#myselect >option').remove(); 
        
        // display the output of the item selected in the div named output
var selected = $("#myselect option:selected"); var output = ""; if(selected.val() != 0){ output = "You Selected " + selected.text(); } $("#output").html(output); } </script> </head> <body> <select id="myselect" name="myselect"> <option value="option1">Option 1</option> <option value="option2">Option 2</option> <option value="option3">Option 3</option> <option value="option4">Option 4</option> </select> <div id="output"></div> </body> </html>
Comments [0] | | # 
# Wednesday, March 11, 2009
Wednesday, March 11, 2009 4:19:23 PM (GMT Standard Time, UTC+00:00) ( jQuery )

 

Here is a working demo

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Using the jQuery loadData method to load an external file</title>
    <script src="jquery-1.2.6.min.js" type="text/javascript"></script>
   
    <script type="text/javascript">
    
    $(document).ready(function() 
    {  $("#loadData").click(function()
       {    
       $(this).text("...One Moment Please...");
            $("#container").append('<div id="favoriteMovies"></div>')            
            .children("#favoriteMovies").hide()
            .load("theOtherPage.htm ul#favoriteMovies", function()
            {
                $("#loadData").remove();                      
                $("#favoriteMovies").slideDown("slow");                     
            });   
            return false;   
        });
    });
    </script>
    
</head>
<body>
<div id="container"> 
    <a href="#" id="loadData">Click This Link To Load My Favorite Movies</a>
</div>
</body>
</html>

theOtherPage.htm

<html xmlns="http://www.w3.org/1999/xhtml">

<head>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252" />
<title>The Other Page</title>
</head>

<body>

<ul id="favoriteMovies">
    <li>My Favorite Movies</li>
    <li>Contact</li><li>Shawshank Redemption</li>
    <li>Napoleon Dynamite</li><li>Back To The Future</li>
    <li>The Goonies</li><li>Cinderella Man</li>
    <li>Apollo 13</li>
</ul>

</body>
</html>
Comments [0] | | # 
# Wednesday, February 18, 2009
Wednesday, February 18, 2009 8:04:55 PM (GMT Standard Time, UTC+00:00) ( jQuery )


I was working on a project at work involving the use of jQuery table sorter and came across another jQuery site which is as equally awesome – jQuery User Interface. The site describes itself as “jQuery UI provides abstractions for low-level interaction and animation, advanced effects and high-level, themeable widgets, built on top of the jQuery JavaScript Library, that you can use to build highly interactive web applications.”  Any type of UI interaction you can think of is probably possible using this library.

Comments [0] | | # 
# Wednesday, December 31, 2008
Wednesday, December 31, 2008 3:47:52 AM (GMT Standard Time, UTC+00:00) ( Javascript/AJAX | jQuery )

Another example of how cool jQuery is.

Here is a working example

<%@ Page Language="VB" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>

<script runat="server">
    Sub Page_Load()

        If Not Page.IsPostBack Then       
            BindGridView()
        End If

    End Sub
    
    Sub BindGridView()
        
        Dim con As New SqlConnection(ConfigurationManager.ConnectionStrings("MyDatabase").ConnectionString)
        Dim strSqlText As String = "SELECT Title, Director FROM Movies"

        Dim cmd As New SqlCommand(strSqlText)
        con.Open()
        cmd.Connection = con

        dgMovies.DataSource = cmd.ExecuteReader(CommandBehavior.CloseConnection)
        dgMovies.DataBind()

        con.Close()
        con.Dispose()
        
    End Sub   
           
</script>

<html>
<head><title></title>
<script type="text/javascript" src="jquery/jquery-1.2.6.min.js"></script>

    <script type="text/javascript">         
         $(document).ready(function() {        
            $("#dgMovies tr").css({ background: "F7F6F3" }).hover(
                function() { $(this).css({ background: "#C1DAD7" }); },
                function() { $(this).css({ background: "#F7F6F3" }); }
                );
        });
    </script>
    
</head>
<body>

<form runat="server">

<asp:gridview runat="server" CellPadding="4" 
ForeColor="#333333" GridLines="None" 
AllowSorting="false" 
id="dgMovies" Width="80%" 
HorizontalAlign="Center" 
Font-Names="Tahoma" 
Font-Size="Small" 
EmptyDataText="No records were found">
    <RowStyle BackColor="#F7F6F3" ForeColor="#333333" />    
    <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
    <HeaderStyle BackColor="Blue" Font-Bold="True" ForeColor="Black" />
    <AlternatingRowStyle BackColor="White" ForeColor="#284775" />
</asp:gridview>

</form>

</body>
</html>
Comments [0] | | # 
Wednesday, December 31, 2008 3:21:57 AM (GMT Standard Time, UTC+00:00) ( Javascript/AJAX | jQuery )

There are many ways to check/uncheck a list of checkboxes using javascript or even in ASP.NET such as in a Gridview.  Using jQuery is probably one of the easiest and most elegant solutions I've found.  Here is an example of how to do it.

<%@ Page Language="VB" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">
    
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
        If (Not Page.IsPostBack) Then
            cb1.Items.Add(New ListItem("Items 1", "Items 1"))
            cb1.Items.Add(New ListItem("Items 2", "Items 2"))
            cb1.Items.Add(New ListItem("Items 3", "Items 3"))
            cb1.Items.Add(New ListItem("Items 4", "Items 4"))
            cb1.Items.Add(New ListItem("Items 5", "Items 5"))
        End If
    End Sub
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="jquery-1.2.6.min.js" type="text/javascript"></script>
    <script type="text/javascript">
    $(document).ready(function() {
            $('#chkAll').click(
             function() {
                 $("INPUT[type='checkbox']").attr('checked', $('#chkAll').is(':checked'));
             });
         });
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:CheckBox ID="chkAll" runat="server" Text="Check All" /><br />
        <asp:CheckBoxList ID="cb1" runat="server">
        </asp:CheckBoxList>
    </div>
    </form>
</body>
</html>

Here is another example which I think is a little simpler than the one above

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Access Values From Multiple or Selected ASP.NET TextBoxes</title>

<script src="http://ajax.Microsoft.com/ajax/jquery/jquery-1.3.2.js" type="text/javascript"></script>

<script type="text/javascript">
$(function() {
    var $chkBox = $("input:checkbox[id$=chkAll]");
    var $tblChkBox = $("table.chk input:checkbox");
        
        $chkBox.click(function() {
            $tblChkBox
            .attr('checked', $chkBox
            .is(':checked'));
        });
        
        // Unchecks chkAll when a checked CheckBox in cbList is unchecked
        
        $tblChkBox.click(
        function(e) {
            if (!$(this)[0].checked) {
            $chkBox.attr("checked", false);
        }
    });
});
</script>
</head>
<body>
<form id="form1" runat="server">

<asp:CheckBox ID="chkAll" runat="server" Text="Check All" ToolTip="Click here to check/uncheck all checkboxes at once"/>
<br /><hr />
    <asp:CheckBoxList ID="cbList" runat="server" class="chk">
        <asp:ListItem Text="Option A" Value="A" />
        <asp:ListItem Text="Option B" Value="B" />
        <asp:ListItem Text="Option C" Value="C" />
        <asp:ListItem Text="Option D" Value="D" />
        <asp:ListItem Text="Option E" Value="E" />
    </asp:CheckBoxList>
<br />

</form>
</body>
</html>
Comments [0] | | #