All posts by Thiyagu

Copy data from div to ClipboardData using Jquery

How to copy div content form div to clipboard

Code Behind File :

Create string builder with some content and assign as like

divcontent.InnerHtml = sbQuestionAndAnswers.ToString();

Design File:

 <div id=”divcontent” style=” width: 1px; height: 1px;overflow:hidden;” runat=”server”></div>

Script File :

if (window.clipboardData && clipboardData.setData) {
if ($(‘#ctl00_cphMain_divcontent’)) {
$(‘#ctl00_cphMain_divcontent’).show();
var editableDiv = $(‘#ctl00_cphMain_divcontent’)

[0];
var txtRange = document.body.createTextRange();
editableDiv.style.display = “”;
txtRange.moveToElementText(editableDiv);
txtRange.select();
txtRange.execCommand(“Copy”);
editableDiv.style.display = “none”;//Hide the div
}}

Note :

Copying the content of div which is bind dynamically form code-behind and it will not display in the page. From that we copy content to clipboard

Nullable Types

Nullable Types

Nullable types are variables that can be assigned with the value ‘null’. Allmost all value types can be declared as a nullable type. To declare a
value type as a nullable type, you have to add a questionmark after the type name.

For example:

char? a = null;
bool? b = null;
int? c = null;
double? d = null;

Nullable type has two read-only properties: HasValue and Value.
HasValue is a bool property. If the current value is ‘null’,
HasValue will return false, otherwise it will return true. The HasValue property can be used to test if a variable contains a value.

For Example :

int? test = 10;
if (test .HasValue)
{
Console.WriteLine(test .Value);
}
else
{
Console.WriteLine(“no value”);
}

How to convert Nullable Type to NON-Nullable Type

int? intValue1 = null;
int intValue2  = intValue1  ?? 10;

Total minutes between two time value

How to get the difference of two time and get MM:SS of  time

Code Behind :

 DateTime locCurrentDateTime = System.DateTime.Now;
TimeSpan difference = locCurrentDateTime.Subtract(Convert.ToDateTime(Session[“starttime”]));
double hrs = Math.Floor(difference.TotalMinutes);
double sec = difference.Seconds;
string time = new DateTime(difference.Ticks).ToString(“mm:ss”);

Note :

output for above code will be find total minutes between two time and formatted as MM:SS

Finding the lable value after clicking the linkbutton inside the gridview

Finding the lable/any control value after clicking the linkbutton inside the gridview

Code Behind File :

  protected void btnClick_Click(object sender, EventArgs e)
{

GridViewRow clickedRow = ((LinkButton)sender).NamingContainer as GridViewRow;
Label lblID = (Label)clickedRow.FindControl(“lblEmpID”);

Session

[“patientEMRID”] = lblID.Text;

}

Note :

First line we finding the clickable row and then finding the label value inside the gridview. lblEmpID is the id of the lable .

Calling severside method form script

How to call server side method button click event from the client side script :

Script :

<%= Page.ClientScript.GetPostBackEventReference(btnClose, String.Empty) %>;

Note :

Place this code in the script to call the any sever-side method, from above btnclose is the click method of the button. and event is empty.

Calling Script method from server side method.

System.Web.UI.ScriptManager.RegisterClientScriptBlock(Page, typeof(Page), “Script”, “ConfirmationAlert();”, true);

Note :

ConfirmationAlert()  method :

 function ConfirmationAlert() {
var copiedText = “”;
var answer = confirm(“Click ‘OK’, to give alert!”)
if (answer) {
alert(“You Click OK”);}}

removeAttr() Method

.removeAttr()

Remove an attribute from each element in the set of matched elements.

HTML :

<table border=”1″>
<tr><td>This is first table</td></tr>
</table>

JQUERY:

$(document).ready(function() {

$(“table”).removeAttr(“border”);

});

OUTPUT DOM :

<table>
<tr><td>This is first table</td></tr>
</table>

NOTE :

From above JQ, removeAttr() remove th border attribute in the selected table

attr() Method

attr() :

The attr() method sets or returns attribute values of selected elements.

Getting attribute

JQUERY : 1

alert($(“#img1”).attr(“href”));

From above JQ, the message box will show the link of img1(which element having id as img1). Here its getting
value of attribute

Set attribute

JQUERY : 2

$(“#img1”).attr(“href”, “http://www.google.in”);

From above JQ, the link will apply to the href in to the element which having id as img1.

Example 1:

HTML :

<body><img /> <img /></body>

JQUERY :

$(“img”).attr({
src: “/image/test.gif”,
title: “jQuery attr() method”,
alt: “Not Available”
});

OUTPUT DOM :

<body>
<img src=”/image/test.gif” title=”jQuery attr() method” alt=”Not Available” />
<img src=”/image/test.gif” title=”jQuery attr() method” alt=”Not Available”/>
</body>

clone() Method

clone()

  •   Create a deep copy of the set of matched elements.
  •   We can use clone copy in to two ways,clone()/clone(true).It also support a boolean parameter to indicate whether need to copy the event handlers and data along with the matched elements.First we see the clone()

METHOD 1 :  clone()

Use clone() to create a copy of the above elements, and place the copied elements after the div tag that contains a class name of  “mainDiv”.

HTML :

<div>
<p>Testing for clone() method in jquery
</div>

JQUERY :

$(‘.mainDiv’).clone().insertAfter(“.mainDiv”);

OUTPUT DOM :

<div>
<p>Testing for clone() method in jquery</p>
</div>

<div>
<p>Testing for clone() method in jquery
</div>

NOTE:
After executing JQ, the element which has class name as mainDiv will be copied and placed after the element which has class name of mainDiv

METHOD 2: clone(boolean)
It also support a boolean parameter to indicate whether need to copy the event handlers and data along with the matched elements.

HTML :

<button id=”cloneBtn”>clone()</button>

JQUERY :

$(“#cloneBtn”).click(function () {

$(‘.mainDiv’).clone().insertAfter(“.mainDiv”);

});

STEP 1 : $(‘#cloneBtn’).clone().insertAfter(“#cloneBtn”);

Above will copy only element without any event handler.

STEP 2 ; $(‘#cloneBtn’).clone(true).insertAfter(“#cloneBtn”);

Above will copy event handler along with matched elements, you should use clone(true).

Note : For better understanding

 If we create button dynamically with the clone method,it will copy element and eventhandler(thats is action to be performed ) when we use
clone(true).

click() vs bind() vs live() vs delegate()

click() vs bind()

Bind an event handler to the “click” JavaScript event, or trigger that event on an element.First, .click(function) is literally a shortcut for .bind(‘click’, function), they are equivalent.
Use them when binding a handler directly to an element.

Example 1:

$( “#div1” ).bind( “click”, function( e ) {

alert(“Click event using bind()”);

});

$( “#members li a” ).click( function( e ) {

alert(“Click event using click()”);

} );

Cons :

  •     The method attaches the same event handler to every matched element in the selection.
  •     It doesn’t work for elements added dynamically that matches the same selector.
  •     There are performance concerns when dealing with a large selection.

Main difference between bind() vs delegate()
Example 2:

$(document).ready(function(){
$(“table”).delegate(“td”,”click”,function(){
alert(‘I am’ + $(this).text());
});
});

If we append new td dynamically in to the above table the click event will be apply for it(ie., it will apply for future
element also), but bind will not bind the event to the future element

bind() vs live()

The advantage of live and delegate function that they attaches event to those elements also which are added/appended after DOM is loaded.

 Example 3:

$(‘a’).live(‘click’, function() { alert(“Thats New!”) });

jQuery binds the alert function to the $(document) element, along with ‘click’ and ‘a’ as parameters. Any time an event bubbles up to the
document node, it checks to see if the event was a click and if the target element of that event matches the ‘a’ CSS selector. If both are true,
the function executes.

Difference :

  • live function can’t be used in chaining. live function needs to be used directly on a selector/element.

    for example : Wrong Code

$(‘#foo’).children(‘table’).find(‘td’).live(‘click’, function(){
});

  for example : Correct code

$(‘#foo’).children(‘table’).find(‘td’).delegate(‘click’, function(){
});

  • There is one more difference in terms of performance, if the context is not specified with the live function. Context means you are setting the search limit within a specific node.If you don’t specify the context with live function then it attaches the handler to the document by default and when executed it traverse through the DOM which causes a performance issue.

$(document).ready(function(){
$(“#tble1 td”).live(“click”,function(){
alert(“test”);
});

});

In the above code, no context is specified so event gets attached to the document by default. It causes a huge performance issue. But with jQuery 1.4, you can specify the context with live function also.

$(document).ready(function(){
$(“td”,$(“#tble1”)

[0]).live(“click”,function(){
alert(“test”);
});
});

click() and dblclick()

click() : Fire when mouse single click on the matched element.

dblclick() : Fire when mouse double clicks on the matched element.

Example :

$(‘#singleClick’).click(function(){

$(‘#singleClick’).css(“border”, “1px solid red”);

});

$(‘#doubleClick’).dblclick(function(){

$(‘#doubleClick’)..css(“border”, “1px solid blue”);
});

Note :

Step 1: Element has id as “singleclick”  will apply border as red ( single click ).
Step 2: Element has id as  “doubleClick”  will apply border as blue in ( double click ).