All posts by Thiyagu

Difference Between jQuery Text() And HTML()

 

In this post you will learn about the difference between jQuery text and HTML.

.html() – This jQuery function gets/sets the HTML of any element.
.text()- This jQuery function gets/sets the text (innertext) of any element.

Let’s take an example. I have placed a div element, which have a span tag as child and some text.

HTML :

This code given below is the sample HTML document

<div id=”dvFirst”>
<span>jQuery By Example </span>
</div>

Now in .ready() event, both the functions .html() and .text() functions are used on div and the output is placed in alert box.

JQUERY :

$(function () {
alert(“Div HTML is: ” + $(“#dvFirst”).html());
alert(“Div content is: ” + $(“#dvFirst”).text());
});

Now, when you view this page in browser, there will be 2 alerts.

First alert box, will display below text.

Div HTML is: <span>jQuery By Example </span>

And second alert box, will display below text.

Div content is: jQuery By Example

As you see, that the .html() function provides you the inner html and text of the element while text function gives you only text.

.append() VS .html()

.append() and .html() is the most usefull method in jQuery.But these are far different from one another,

.append() add some value with the existing one. whether .html() do the same but it removes the old value

HTML :

<ul id=”test”>
<li>test</li>
</ul>

Now use .append() to add one <li>,

<script type=”text/javascript>”
jQuery(“#test”).append(“<li>test1</li>”);
</script>

The output of this jQuery will be

<ul id=”test”>
<li>test</li>
<li>test1</li>
</ul>

Now if I use .html() to add one <li>, For that I will write

<script type=”text/javascript>”
jQuery(“#test”).html(“<li>test1</li>”);
</script>

The output of this Script will be

<ul id=”test”>
<li>test1</li>
</ul>

Here in this example .append() add one extra <li>, whether .html() removes the old one with new one.
This is the main difference between .append() and .html() in Jquery

Query append() VS appendTo()

Query append() and appendTo()

append() :  Append to end of the selected element

HTML :   <ul id=”test”>
<li>test</li>
</ul>
JQuery :   jQuery(“#test”).append(“<li>test1</li>”);

OUTPUT :  <ul id=”test”>
<li>test</li>
<li>test1</li>
</ul>
appendTo :  Append to end of the selected element

HTML :   <div>Hello</div>

JQuery :  $(‘<p>Test</p>’).appendTo(‘.inner’);

OUTPUT :  <div  class=”inner” > Hello
<p>Test</p>
</div>

Difference:
Both jQuery append() and appendTo() methods are doing the same task, add a text or html
content after the content of the matched elements. The major difference is in the syntax.

//Create our content
var appendHTML = “<p>I’m going to be added to the DOM</p>”;

//Select our element, then add the html
$(“#container”).append(appendHTML);

//Create our content, then select the element to append to
$(appendHTML).appentTo(“#container”);

JQuery Selector

JQUERY SELECTORS :

1) selecting a particular element having a specific class

$(“.class1”).css(“border”, “1px solid red”);

2) select all elements of the page

$(“*”).css(“border”, “1px solid red”);

3) select an element that having a particular id

$(“#p1”).css(“border”, “1px solid red”);

4) select all specific elements type

$(“p”).css(“border”, “1px solid red”);

5) select multiple elements in a single selector

$(“div.class1, #div1”).css(“border”, “1px solid red”);

Note : From above the selector first select div having the class name with
            “.class1” and select element having id as “div1”  

 6) select a specific child of the parent element

$(“#div2 p:nth-child(2)”).css(“border”, “1px solid red”);

Note : select the 2nd paragraph (p) element that is inside the div
             element whose id is “div2” and apply the css on the element

7) select last child of the parent element

$(“#div2 p:last-child”).css(“border”, “1px solid red”);

8) select the first child of the parent element

$(“#div2 p:first-child”).css(“background”, “red”);

Note : select the first paragraph (p) element which is inside the
            div element whose id is “div2” and  apply the css on the element.

9) select an element based on its attribute

$(‘input[id$=”txtAddress”]’).val(‘Testing’);

Note : select the textboxes having id ending with “txtAddress” and set its value as “Testing”.

Issue While exporting Gridview to Excel while deployment

Issue While exporting Gridview to Excel

 Issue    : Image is not showing in the Excel

 Solution : The URL must be

ImageUrl=”http://localhost:63360/Website/Images/help.gif” /> instead of ImageUrl=”~/help.gif”.

 So place URL in webcofig

<add key=”ImagePath” value=”http://localhost:63360/Website/Images/”/>

CodeBind :

imgStat.ImageUrl = ConfigurationSettings.AppSettings[“ImagePath”].ToString() + @”help.png”;

find the div inside the Gridview

How to find the div inside the Gridview (outside of gridview function)

.aspx file

<div id=”tooltip” style=”display: none;”></div>

Code Behind file

Make hide of the div

foreach (GridViewRow row in gvdStatus.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{

HtmlGenericControl dive = new HtmlGenericControl();
dive = ((HtmlGenericControl)(row.FindControl(“tooltip”)));
dive.Visible = false;
}
}

Applying color to the row based on the condition

if (e.Row.RowType == DataControlRowType.DataRow)
{
if (Convert.ToInt32(e.Row.Cells

[2].Text) > 525)
{
e.Row.BackColor = System.Drawing.Color.Blue;
}
}

Note :

A table can have header data or footer rows. The above statement will make sure that the row is data row.
row.RowType == DataControlRowType.DataRow: use it every time if you want to look for something in every row.

Custom Paging with Numbers

Custom Paging with Numbers

.aspx File

<div>
PageSize:
<asp:DropDownList ID=”ddlPageSize” runat=”server” AutoPostBack=”true” OnSelectedIndexChanged=”PageSize_Changed”>
<asp:ListItem Text=”10″ Value=”10″ />
<asp:ListItem Text=”25″ Value=”25″ />
<asp:ListItem Text=”50″ Value=”50″ />
<asp:ListItem Text=”75″ Value=”75″ />
</asp:DropDownList>
<hr />
<asp:GridView ID=”gvCustomerDetails” runat=”server”>
</asp:GridView>
<br />
<asp:Button ID=”btnprev” Text=”<<” OnClick=”MovetoPrev” runat=”server” />
<asp:Repeater ID=”rptPage” runat=”server”>
<ItemTemplate>
<asp:LinkButton ID=”lnkPage” runat=”server” Text='<%#Eval(“Text”)%>’ CommandArgument='<%# Eval(“Value”) %>’
OnClick=”GettingPageIndex”></asp:LinkButton>
</ItemTemplate>
</asp:Repeater>
<asp:Button ID=”btnnext” Text=”>>” OnClick=”MovetoNext” runat=”server” />
</div>

.Cs
#region Using Namespaces
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using CustomerDetail;
using System.Web.UI.WebControls;
#endregion

public partial class GridViewPagingWithNumbers : System.Web.UI.Page
{
#region Private Constants
private const string SQL_CONNECTION = “Data Source=DBSRV;Initial Catalog=Shopping;User ID=sa;Password=sa”;
private const string SQL_SPNAME = “[sproc_GetCustomersDetails]”;
#endregion

#region Public Variables
public static int PAGE_NUMBER = 1;
public int RECORD_COUNT;
public static int PAGE_SIZE = 10;
#endregion

protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
LoadCustomerDetails();
}
}

#region Load Customer Records
private void LoadCustomerDetails()
{
var CustomerDetails = new List<CustomerDetails>();
#region Fetching and Loading the Customer Details
try
{
using (var sqlConn = new SqlConnection(SQL_CONNECTION))
{
using (var sqlCmd = new SqlCommand(SQL_SPNAME, sqlConn))
{
sqlCmd.Parameters.AddWithValue(“@PageNo”, PAGE_NUMBER);
sqlCmd.Parameters.AddWithValue(“@PageSize”, PAGE_SIZE);
sqlCmd.CommandType = CommandType.StoredProcedure;
sqlConn.Open();
using (var sqlDataReader = sqlCmd.ExecuteReader())
{
while (sqlDataReader.Read())
{
CustomerDetails.Add(new CustomerDetails(Convert.ToInt32(sqlDataReader[“ID”]), Convert.ToString(sqlDataReader[“CustomerName”]),
Convert.ToString(sqlDataReader[“EmailID”]), Convert.ToString(sqlDataReader[“PhoneNo”])
));
}
sqlDataReader.NextResult();
sqlDataReader.Read();
RECORD_COUNT = Convert.ToInt32(sqlDataReader[“TotalRec”]);
}
}
gvCustomerDetails.DataSource = CustomerDetails.AsReadOnly();
gvCustomerDetails.DataBind();
this.CreatePages(RECORD_COUNT, PAGE_SIZE);
}
}
catch (Exception ex)
{
throw ex;
}
#endregion
}
#endregion

private void  CreatePages(int recordCount, int currentPage)
{
double dblPageCount = (double)((decimal)recordCount / decimal.Parse(ddlPageSize.SelectedValue));
int pageCount = (int)Math.Ceiling(dblPageCount);
List<ListItem> pages = new List<ListItem>();
if (pageCount > 0)
{
pages.Add(new ListItem(“First”, “1”));
if (PAGE_NUMBER >= 10 && (PAGE_NUMBER) <= pageCount )
{
for (int loop_Index = PAGE_NUMBER-5; loop_Index < PAGE_NUMBER + 5; loop_Index++)
{
pages.Add(new ListItem(loop_Index.ToString(), loop_Index.ToString()));
}
}
else
{
for (int loop_Index = 1; loop_Index <= 10; loop_Index++)
{
pages.Add(new ListItem(loop_Index.ToString(), loop_Index.ToString()));
}

}

pages.Add(new ListItem(“Last”, pageCount.ToString()));
}
rptPage.DataSource = pages;
rptPage.DataBind();
}
protected void PageSize_Changed(object sender, EventArgs e)
{
PAGE_SIZE = Convert.ToInt32(ddlPageSize.SelectedValue);
PAGE_NUMBER = 1;
LoadCustomerDetails();
}
protected void GettingPageIndex(object sender, EventArgs e)
{
PAGE_NUMBER = int.Parse((sender as LinkButton).CommandArgument);
LoadCustomerDetails();
}
protected void MovetoNext(object sender, EventArgs e)
{
PAGE_NUMBER++;
LoadCustomerDetails();
}
protected void MovetoPrev(object sender, EventArgs e)
{
PAGE_NUMBER–;
LoadCustomerDetails();
}
}

CustomerDetails.cs

#region Using Namespaces
using System;
using System.Data;
using System.Configuration;
using System.Web;
#endregion

namespace CustomerDetail
{
public class ConnectionDetails
{
#region Public Method
public string ConnectionInfo
{
get
{
return ConfigurationSettings.AppSettings[“myConnectionString”].ToString();
}
}
#endregion
}

public class CustomerDetails
{
#region Private Members
private readonly int c_id;
private readonly string c_email;
private readonly string c_phoneNumber;
private readonly string c_name;
#endregion

#region Public Members
public int ID
{
get { return c_id; }
}
public string Name
{
get { return c_name; }
}
public string Email
{
get { return c_email; }
}
public string PhoneNumber
{
get { return c_phoneNumber; }
}
#endregion

#region Public Const.
public CustomerDetails(int pID, string pName, string pEmail, string pPhoneNumber)
{
c_id = pID;
c_email = pEmail;
c_name = pName;
c_phoneNumber = pPhoneNumber;
}
#endregion

}

}

Stored Procedure

ALTER PROCEDURE [dbo].[sproc_GetCustomersDetails]
@PageNo        INT,
@PageSize    INT
AS
BEGIN
SET NOCOUNT ON;

DECLARE @StartIndex INT, @EndIndex INT, @TotalRec INT, @TotalPages INT;

SELECT @TotalRec = COUNT(1) FROM [tCustomer] WITH (NOLOCK)
WHERE [CustomerName] IS NOT NULL;

IF @PageNo <= 0 SET @PageNo = 1;
IF @PageSize <= 0 SET @PageSize = 1;
IF @PageSize > @TotalRec SET @PageSize = @TotalRec;

SET @TotalPages = CEILING(@TotalRec * 1.0 / @PageSize);
IF (@PageNo > @TotalPages) SET @PageNo = @TotalPages;

SET @StartIndex = (@PageNo – 1) * @PageSize + 1;
SET @EndIndex =  @StartIndex + @PageSize – 1;

IF @StartIndex > @TotalRec SET @StartIndex = @TotalRec;
IF @EndIndex > @TotalRec SET @EndIndex = @TotalRec;

WITH [Customer] AS
(
SELECT ROW_NUMBER() OVER (ORDER BY [CustomerName] ASC) AS [RowNo], [ID]
FROM [tCustomer] WITH (NOLOCK)
WHERE [CustomerName] IS NOT NULL
)
SELECT
[I].[ID],
[I].[CustomerName],
[I].[EmailID],
[I].[PhoneNo]
FROM [tCustomer] AS [I] WITH (NOLOCK)
INNER JOIN [Customer] AS [II] WITH (NOLOCK) ON [II].[RowNo] BETWEEN @StartIndex AND @EndIndex AND [II].[ID] = [I].[ID]
ORDER BY [II].[RowNo] ASC;

SELECT @TotalPages AS [TotalPages], @TotalRec AS [TotalRec];
END;