Navigation

Search

Categories

On this page

How to retrieve the list of checked values from a checkboxlist control
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
Accessing Multiple Textbox Values Using Query
Using jQuery to Hide Rows or Columns in a Gridview
Exporting Data From a Gridview to Excel
Basic jQuery Selectors
WSS setsitelock Parameter
Using jQuery to Filter Table Values
JTIP – jQuery Tooltip
Clearing Form Fields

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: 378
This Year: 6
This Month: 1
This Week: 0
Comments: 17

Sign In
Pick a theme:

# Thursday, December 31, 2009
Thursday, December 31, 2009 4:37:41 PM (GMT Standard Time, UTC+00:00) ( ASP.NET )
Here's an example of how to retrieve the list of checked values from a checkboxlist control

Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim MyItem As ListItem
        For Each MyItem In CheckBoxList1.Items
            If MyItem.Selected = True Then
                Response.Write(MyItem.Value)
                Response.Write("<br/>")
            End If
        Next
End Sub


Here's an example of how to retrieve the list of checked values from a checkboxlist control and add them 
to an arraylist.
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click Dim chkvalues As ArrayList = New ArrayList() For Each chkBoxListItem As ListItem In CheckBoxList1.Items If (chkBoxListItem.Selected) Then chkvalues.Add(chkBoxListItem.Value) End If Next chkBoxListItem Session("CheckedItems") = chkvalues Response.Redirect("Default2.aspx") End Sub To retrieve the values of how to retrieve those values from the arraylist. Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load If Not (Session("CheckedItems") Is Nothing) Then Dim chkvalues As ArrayList = CType(Session("CheckedItems"), ArrayList) For Each chkBoxListItemValue As String In chkvalues Response.Write(System.Environment.NewLine + chkBoxListItemValue) Next chkBoxListItemValue End If End Sub
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] | | # 
Monday, December 21, 2009 6:38:55 PM (GMT Standard Time, UTC+00:00) ( )


To achieve this requirement, a common technique adopted by developers is to iterate through a set of controls, apply a filter and then collect the results in a new array. $.map() is an extremely useful function which saves us from writing these steps. This function transforms an array into another array by using a
filter function and then allows us to access individual items of the array and modify them.

In this code, on the first button (btnAll) click, the postback is prevented using e.preventDefault(). The content of the paragraph is reset ($("#para").text('')) and we then use a selector to match all input elements of type text (input:text). The $.map() method iterates through all the textboxes on the page and invokes a filter function to select the non-empty textboxes. The results are appended to a paragraph (divResults) and displayed individually using a line break (<br/>).

Here is a working demo.

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Access Values From Multiple/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() {
        $('input[id$=btnAll]').click(function(e) {
        e.preventDefault();
        $("#divResults").text('')
            .append($("input:text").map(function() {
            return $(this).val() || null;
            }).get().join("<br/> "));
    });
    
    $('input[id$=btnSelected]').click(function(e) {
        e.preventDefault();
        $("#divResults").text('')
            .append($("input.selected").map(function() {
            return $(this).val() || null;
            }).get().join("<br/> "));
        });
    });
</script>
</head>

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

    <h2>Access Values From Multiple/Selected ASP.NET TextBoxes</h2>
    
    <asp:TextBox ID="txt1" runat="server" Text="Text Box 1" /><br />
    <asp:TextBox ID="txt2" runat="server" Text="Text Box 2"/><br />
    <asp:TextBox ID="txt3" runat="server" Text="Text Box 3"/><br />
    <asp:TextBox ID="txt4" runat="server" Text="Text Box 1 (class-selected)" class="selected" /><br />
    <asp:TextBox ID="txt5" runat="server" Text="Text Box 4"/><br />
    <asp:TextBox ID="txt6" runat="server" Text="Text Box 2 (class-selected)" class="selected" /><br /><br />
    
    <asp:Button ID="btnAll" runat="server" Text="Display All" ToolTip="Click to display text from all boxes" /><br />
    <asp:Button ID="btnSelected" runat="server" Text="Display Selective" ToolTip="Click to display text from boxes with class-selected" />
    <br/>
    Tip: Clicking on the 'Display Selective' button retrieves<br />
    values from only those TextBoxes which have 'class=selected'
    <p id="divResults"></p>

</form>
</body>
</html>
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] | | # 
# Thursday, December 17, 2009
Thursday, December 17, 2009 3:26:57 PM (GMT Standard Time, UTC+00:00) ( ASP.NET | Gridview )


There are many examples of this online and I’ve posted one myself. When using an updatepanel with your Gridview, it’s common to receive the error message I  "Control 'GridView1' of type 'GridView' must be placed inside a form tag with runat=server. " Just setting EnableEventValidation="false" in the page directive won’t work in this case.

<%@ Import Namespace="System.IO" %>

<asp:button id="btnExportExcel" Text="Export to Excel" onclick="ExcelExport" runat="server" />

 Sub ExcelExport(ByVal Source As Object, ByVal E As EventArgs)
        Export("CompanyList.xls", GridView1)
    End Sub

    Public Shared Sub Export(ByVal fileName As String, ByVal gv As GridView)
        HttpContext.Current.Response.Clear()
        HttpContext.Current.Response.AddHeader("content-disposition", String.Format("attachment; filename={0}", fileName))
        HttpContext.Current.Response.ContentType = "application/ms-excel"
        Dim sw As StringWriter = New StringWriter
        Dim htw As HtmlTextWriter = New HtmlTextWriter(sw)
        '  Create a form to contain the grid
        Dim table As Table = New Table
        table.GridLines = gv.GridLines
        '  add the header row to the table
        If (Not (gv.HeaderRow) Is Nothing) Then
            PrepareControlForExport(gv.HeaderRow)
            table.Rows.Add(gv.HeaderRow)
        End If
        '  add each of the data rows to the table
        For Each row As GridViewRow In gv.Rows
            PrepareControlForExport(row)
            table.Rows.Add(row)
        Next
        '  add the footer row to the table
        If (Not (gv.FooterRow) Is Nothing) Then
            PrepareControlForExport(gv.FooterRow)
            table.Rows.Add(gv.FooterRow)
        End If
            
        '  render the table into the htmlwriter
        table.RenderControl(htw)
        '  render the htmlwriter into the response
        HttpContext.Current.Response.Write(sw.ToString)
        HttpContext.Current.Response.End()
    End Sub

    ' Replace any of the contained controls with literals
    Private Shared Sub PrepareControlForExport(ByVal control As Control)
        Dim i As Integer = 0
        Do While (i < control.Controls.Count)
            Dim current As Control = control.Controls(i)
            If (TypeOf current Is LinkButton) Then
                control.Controls.Remove(current)
                control.Controls.AddAt(i, New LiteralControl(CType(current, LinkButton).Text))
            ElseIf (TypeOf current Is ImageButton) Then
                control.Controls.Remove(current)
                control.Controls.AddAt(i, New LiteralControl(CType(current, ImageButton).AlternateText))
            ElseIf (TypeOf current Is HyperLink) Then
                control.Controls.Remove(current)
                control.Controls.AddAt(i, New LiteralControl(CType(current, HyperLink).Text))
            ElseIf (TypeOf current Is DropDownList) Then
                control.Controls.Remove(current)
                control.Controls.AddAt(i, New LiteralControl(CType(current, DropDownList).SelectedItem.Text))
            ElseIf (TypeOf current Is CheckBox) Then
                control.Controls.Remove(current)
                control.Controls.AddAt(i, New LiteralControl(CType(current, CheckBox).Checked))
                'TODO: Warning!!!, inline IF is not supported ?
            End If
            If current.HasControls Then
                PrepareControlForExport(current)
            End If
            i = (i + 1)
        Loop
    End Sub
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 8:01:52 PM (GMT Standard Time, UTC+00:00) ( Sharepoint )


I recently backed up our WSS 3.0 site using the STSADM command line tool and after it was finished every WSS site collection was marked read-only and none of our users could edit the sites.  I knew the backup using the stsadm tool put the site in read-only mode during backups but was mystified why it kept it that way when the backup was completed. It seems the force and nositelock parameters were first introduced in Windows SharePoint Services 3.0 with Service Pack 2 (SP2).

If changes are made to the site collection during the backup process, the backup can become corrupted. Backing up large site collections can take a long time. To reduce the chance that user activity will interfere with a site collection backup, or that the time that is required to back up large site collections will exceed the available maintenance window, follow these recommendations:

■ Do not use the Stsadm backup operation for site collections larger than 15 gigabytes (GB). For larger site collections, see the recommendations in Back up and restore site collections by using built-in tools (Windows SharePoint Services 3.0).

■ For the duration of the backup, set the site collection URL to read-only by using the Setsitelock: Stsadm operation (Windows SharePoint Services). This lets users view content on the site, but prevents activities such as adding or changing content that interfere with the backup process. When the backup is complete, return the access setting of the site collection URL to its default state.
In Service Pack 2 for SharePoint Products and Technologies, site collections are automatically locked as read-only before a backup process occurs. Therefore, there is no need to use the Setsitelock: Stsadm operation (Windows SharePoint Services) operation. If you do not want site collections to be locked as read-only, you must specify the nositelock parameter that is available in Windows SharePoint Services 3.0 with Service Pack 2 (SP2).

Setsitelock: Stsadm operation (Windows SharePoint Services)

To determine the lock status of the site, you can use the following getsitelock syntax
C:\>stsadm -o getsitelock -url http://tclconnect

Once the lock status of the site collection is determined, you can use the noaccess parameter of the setsitelock operation to lock out all users to the site:

stsadm -o setsitelock -url http://server_name -lock noaccess

You can use the Backup operation to create a backup of the site collection:

stsadm -o backup -url http://server_name -filename "filename.bak" -overwrite

After the site has been backed up, you can use the none parameter of the setsitelock operation to remove all locks to the site:

stsadm -o setsitelock -url http://server_name -lock none

Here’s a copy of the bat file that gets run to back up our WSS site using Windows Scheduler

@echo off
echo ====================================================
echo Backup Script For Office SharePoint Server 2007
echo ====================================================
cd c:\program files\common files\microsoft shared\web server extensions\12\bin
@echo off
stsadm -o Backup -nositelock -url http://tclconnect -filename d:\sharepointbackups\backup.bak -backupmethod full -overwrite
Comments [0] | | # 
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] | | # 
Friday, December 04, 2009 3:26:50 AM (GMT Standard Time, UTC+00:00) ( ASP.NET | VB.NET )

 

Here is a server-side approach to clearing all form fields on a form when a button is clicked.

    Protected Sub btnClearFields_Click(ByVal sender As Object, ByVal e As System.EventArgs)
        'First clear all form fields of any existing values
        EmptyTextBoxValues(Me)
    End Sub

    Private Sub EmptyTextBoxValues(ByVal parent As Control)
        For Each c As Control In parent.Controls
            If (c.Controls.Count > 0) Then
                EmptyTextBoxValues(c)
            Else
                If TypeOf c Is TextBox Then
                    CType(c, TextBox).Text = ""
                End If
            
                If TypeOf c Is Dropdownlist Then
                    CType(c, Dropdownlist).SelectedValue = ""
                End If
                
                If TypeOf c Is ListBox Then
                    CType(c, ListBox).SelectedValue = ""
                End If
                
                If TypeOf c Is CheckBox Then
                    CType(c, CheckBox).Checked = False
                End If
            End If
        Next
    End Sub
Comments [0] | | #