interviews.dotnetthread.com

↑ Grab this Headline Animator

Friday, July 3, 2009

Alternative: $(document).ready handler will not be fired on asynchronous postback.

Like in case we are using updatepanel under which we have postback button along with jQuery calender textbox.

And datepicker is attached to a textbox in document ready event handler.

Upon postback jquery calender will not work as $(document).ready will not be called on
asynchronous postback
so to make sure this to work we have to call a Javascript function after an UpdatePanel asynchronous postback using the following line


Sys.WebForms.PageRequestManager.getInstance().add_endRequest(showdatepicker);


here showdatepicker is a function which will attach jQuery datepicker to a textbox.

Submit this story to DotNetKicks

Sunday, June 7, 2009

Fundamentals of jQuery


Introduction:
. jQuery is a fast, lightweight JavaScript library that is CSS3 compliant and supports many browsers.
. The jQuery framework is extensible and very nicely handles DOM manipulations, CSS, AJAX, Events and Animations.
Selector: An expression for identifying target elements on a page that allows us to easily identify and grab the elements we need.
. jQuery focuses on retrieving elements from our HTML pages and performing operations upon them.

<button
type="button"
onclick="document.getElementById('xyz').style.color='red';">
Click Me
</button>

window.onload = function() {
document.getElementById('testButton').onclick = makeItRed;
};


. Consistent across all browsers.
. Solves major javascript problems
. Easily extendable

jQuery wrapper
. To collect a group of elements, we use the simple syntax $(selector) or jQuery(selector)
. The $() function (an alias for the jQuery() function) returns a special Java-Script object containing an array of the DOM elements that match the selector.
. This object possesses a large number of useful predefined methods that can acton the group of elements.
. This type of construct is termed a wrapper because it wraps the matching element(s) with extended functionality. $("div.notLongForThisWorld").fadeOut();
. A special feature of a large number of these methods, which we often refer to as jQuery commands, is that when they’re done with their action (like a fading-out operation), they return the same group of elements, ready for another action. $("div.notLongForThisWorld").fadeOut().addClass("removed");

. Along with selectors that we already know jQuery supports all selectors in CSS and also custom selectors
Here are a few examples.

$("p:even"); - This selector selects all even <p> elements.
$("tr:nth-child(1)"); - This selector selects the first row of each table.
$("body > div"); - This selector selects direct <div> children of <body>.
$("a[href$=pdf]"); - This selector selects links to PDF files.
$("body > div:has(a)") - This selector selects direct <div> children of <body>-containing links. http://docs.jquery.com/Selectors

Utility functions

. jQuery’s $() function – along with wrapping elements to be operated upon it serves as a namespace prefix for a handful of general purpose Utility functions.
. Notation: $.trim(someString); / jQuery.trim(someString);


The document ready handler
. Unobtrusive JavaScript - behavior is separated from structure
We willll be performing operations on the page elements outside of the document markup that creates them. In order to achieve this, we need a way to wait until the DOM elements of the page are fully loaded before those operations execute.
. In the zebra-striping example, the entire table must load before striping can be applied.
window.onload = function() {
$("table tr:nth-child(even)").addClass("even");
};
. The onload handler for the window instance is used for this purpose, executing statements after the entire page is fully loaded.
. Browser will delay calling onload till DOM tree is created and all images/other external
resources are fully loaded.
. Better approach would be to wait till DOM tree is ready and before executing scripts to apply rich behavior. jQuery provides a simple means to trigger the execution of code once the DOM tree, but not external image resources, has loaded.
$(document).ready(function() {
$("table tr:nth-child(even)").addClass("even");
});
. We can use this technique multiple times within the same HTML document


Extending jQuery

. jQuery is designed to be easily extended with additional functionality.
. jQuery makes it easy to extend its set of functions by extending the wrapper returned when we call $().

$.fn.disable = function()
{
return this.each
(
function()
{
if (typeof this.disabled != "undefined") this.disabled = true;
}
);
}

. Our brand new disable() method will support chaining like many of the native jQuery methods. We’ll be able to write
$("form#myForm input.special").disable().addClass("moreSpecial");

. Moreover, enterprising jQuery users have extended jQuery with sets of useful
functions that are known as plugins.

Selecting and Manipulating elements

Selectors Lab: http://www.aacr9.com/jquery/jQueryInAction/jqia.source/chapter2/lab.selectors.html http://www.codylindley.com/jqueryselectors/
. Using the basic CSS selectors like
■ a—This selector matches all link (<a>) elements.
■ #specialID—This selector matches elements that have an id of specialID.
■ .specialClass—This selector matches elements that have the class of specialClass.
■ a#specialID.specialClass—This selector matches links with an id of specialID and a class of specialClass.
■ p a.specialClass—This selector matches links with a class of specialClass declared within <p> elements.

. To select elements using jQuery, we wrap the selector in $() Ex: $("p a.specialClass")
. With a few exceptions , jQuery is fully CSS3 compliant.
. jQuery doesn’t depend upon the CSS implementation of the browser it’s running within. Even if the browser doesn’t implement a standard CSS selector correctly, jQuery will correctly select elements according to the rules of the World Wide Web Consortium (W3C) standard.
. Using child, container, and attribute selectors

. Only a single level of nesting is supported. Although it’s possible to nest one level , such as foo:not(bar:has(baz)) , li:not(:has(a)) additional levels of nesting, such as foo:not(bar:has(baz:eq(2))) aren’t supported.
Selecting by position:
. Sometimes, we’ll need to select elements by their position on the page or in relation to other elements. We might want to select the first link on the page, or every other paragraph, or the last list item of each list.
. For more advanced selectors, jQuery uses the next generation of CSS supported by Mozilla Firefox, Internet Explorer 7, Safari, and other modern browsers.
. These advanced selectors include selecting the direct children of some elements, elements that occur after other elements in the DOM, and elements with attributes matching certain conditions.

. Only a single level of nesting is supported. Although it’s possible to nest one level , such as foo:not(bar:has(baz)) , li:not(:has(a)) additional levels of nesting, such as foo:not(bar:has(baz:eq(2))) aren’t supported.
Selecting by position:
. Sometimes, we’ll need to select elements by their position on the page or in relation to other elements. We might want to select the first link on the page, or every other paragraph, or the last list item of each list.


. The nth-child selector starts counting from 1, whereas the other selectors start counting from 0.
. :eq (absolute position selector) is 0-based, but :nth-child is 1-based.



. Ex: To select only enabled checked checkboxes :checkbox:checked:enabled

. Using the :not filter – To inverse all these filters To select non-check box <input> elements, we use
input:not(:checkbox)
. We can apply the :not filter to filter selectors, but not to find selectors. The
Selector div p:not(:hidden) is a perfectly valid selector, but div :not(p:hidden) isn’t.
. Along with all these selectors we have a plugin “Basic Xpath”. This plugin adds in basic XPath selector functionality
. Plug-in supports /, //, *,[@p=value],[@p], position()
$("<div>Hello</div>")
. This expression creates a new <div> element ready to be added to the page
. We can run any jQuery commands that we could run on wrapped element sets of existing elements on the newly created fragment.
. $("<div class=‘test'>I have foo!</div><div>I don't</div>").filter(".test").click(function() {
alert("I'm foo!");}).end().appendTo("#someParentDiv");
. We can get a lot accomplished without writing a lot of script.

. Determining the size of the wrapped set $('a').size()
. Obtaining elements from the wrapped set jQuery allows us to treat the wrapped set as a JavaScript array, we can use simple array indexing to obtain any element in the wrapped list by position. $('img[alt]')[0] or $('img[alt]').get(0) Ex: var allLabeledButtons = $('label+button').get();
. Adding more elements to the wrapped set Let’s say that we want to match all elements that have either an alt or a title attribute. $('img[alt],img[title]') or $('img[alt]').add('img[title]') $('img[alt]').add(someElement) $('p').add('<div>Hi there!</div>')
. $('img[alt]').addClass('thickBorder').add('img[title]‘).addClass('seeThrough')
not() method to remove elements from the wrapped set anywhere within a jQuery chain of commands - $('img[title]').not('[title*=puppy]')
the selectors we can pass to the not() method are limited to filter
. Expressions that omit any element reference (allowing it to imply all element types).

. In case we want to filter the wrapped set in ways that are difficult or impossible to express with a selector expression. Instead of iterating through all the elements we can use jQuery’s filter()
. The filter() method, when passed a function, invokes that function for each wrapped element and removes any element whose function invocation returns the value false.
. Each invocation has access to the current wrapped element via the function context (this) in the body of the filtering function. Any element that returns an invocation of false is removed from the set.
Ex : $('td').filter(function(){return this.innerHTML.match(/^\d+$/)})
. The filter() method can also be used with a passed selector expression that conforms to the same constraints that we described earlier for the not() method, namely, filter selectors with an implied element type.
$('img').addClass('seeThrough').filter('[title*=dog]‘).addClass('thickBorder')
. Subsets of the wrapped set To obtain a subset of the wrapped set, based on the position of elements within the set.
. slice(begin,end)
. To grab elements from the end of the wrapped set, the statement - $('*').slice(4);
. Getting wrapped sets using relationships These methods give us a large degree of freedom to select elements from the DOM, based on relationships to the other DOM elements.

. The find() method lets us search through an existing wrapped set and returns a new set that contains all elements that match a passed selector expression. - wrappedSet.find('p cite')
. jQuery also provides a method to find elements that contain a specified string. - $('p').contains('Lorem ipsum')
. The is() method returns true if at least one element matches the selector, and false if not . - is(selector)
. The easiest way to inspect or modify the component elements of a matched set is with the each() command.
Ex: $('img').each(function(n)
{
this.alt='This is image['+n+'] with an id of '+this.id;
});
. To collect all values for a specific property into an array using each(), as follows:
var allAlts = new Array();
$('img').each(function(){
allAlts.push(this.alt);
});
. var altValue = $('#myImage')[0].alt;
. attr(name) - To obtain the values assigned to the specified attribute for the first element in the matched set. - $("#myImage").attr("custom")
. Setting attribute values: attr(name,value)
. Setting multiple attributes at a time: attr(attributes) Ex: $('input').attr({ value: '', title: 'Please enter a value' });
. Removing Attributes: removeAttr(name)
. jQuery attr() normalized-access names

.Changing Element Styling:
addClass(names)
removeClass(names)
toggleClass(name)
css(name,value) – Applying Styles directly onto the elements
css(properties)
css(name)

Submit this story to DotNetKicks

Sunday, May 24, 2009

Rounding a number after decimal point using Vb script Format functions

Below is the function in the vbscript which will round the number up to two digits after decimal number.



<Script language="VBScript">

Function Roundnumber(Decnumber,numlength)

Roundnumber = FormatCurrency(Decnumber,numlength,,,0)

Roundnumber = FormatNumber(Decnumber,numlength,,,0)

End Function

</Script>

<Script language="JavaScript">

function roundnumjavascript(number,length)

{

document.getElementById('textBox1').value= Roundnumber(number,length)

}

</Script>

In HTML

<input type="text" id="textBox1"/>

<input type="button" id="btnround" value="Roundnum" onclick="roundnumjavascript(document.getElementById('textBox1').value,2);"/>

Submit this story to DotNetKicks

Calling VB Script Function from inside a Javascript function.

Calling VB script function in javascript is as simple as calling another javascript function.

Let us see with a simple example.
First we will create a function in VB Script to add two numbers.

Call this VB Script function from javascript

Following is html page to input values to add and shows the result in other


<html>

<head>

<script language="VbScript">



Function Add(a,b)

Add=CInt(a)+CInt(b)

End Function



</script>



<script language="JavaScript">



function callingVbfun()

{

document.getElementById('txtResult').value= Add(document.getElementById('txtNumber1').value,document.getElementById('txtNumber2').value)

}



</script>

</head>

<body></body>

<form>

<input type-"text" id="txtNumber1"/>

<input type-"text" id="txtNumber2"/>

<input type-"text" id="txtResult"/>

<input type-"button" id="btn" value="Add" onclick="callingVbfun()"/>

</form>

</html>

Submit this story to DotNetKicks

Thursday, May 14, 2009

How to call multiple Javascript methods on window load using onload handler

We know that when we cannot assign mutilple functions to onload handler in javascript. It will just ovveride the previous function.

In order to set mutliple functions we need to consider Array and add all methods to that array.(functions can be added in Page or Usercontrol).

First Create onloadManager array.


if (!window.onloadManager)
{
window.onloadManager = new Array();

//add existing method to array

if (window.onload) {window.onloadManager[0] = window.onload;}

//Loop through array and execute each on onload
window.onload = function() {
for (index in window.onloadManager) { window.onloadManager[index](); }
};
}



Adding functions to onloadmanager array.

window.onloadManager[window.onloadManager.length] = function()
{

alert('function1 added');

};

Say in other user control on same page we add one more function.

window.onloadManager[window.onloadManager.length] = function()
{

alert('function2 added');

};

Submit this story to DotNetKicks

Wednesday, April 22, 2009

Migrating from VS2005,.NET Framework 2.0 to VS2008 and .NET Framework 3.5

When we open our solution developed in Visual Studio 2005 and .Net 2.0 it will automatically converts the solution and all projects under it, to be compatible with Visual Studio 2008 and to use new compiler. A wizard will be displayed during this process.

Then we can target each project under solution to .NET Framework 3.5/3.0/2.0 by changing the Target Framework property for a project.

Once converted to Visual Studio 2008, we cannot open it in previous versions.

Based on conversion report we may have to change few classes and used namespaces.

As .Net Framework 3.5 is built on 2.0 we cannot remove .NET 2.0 Framework in the web server.
No need to change anything in IIS while deploying.

However even if our project is developed in VS2008 by targeting to .NET Framework 2.0 while deploying in the server we need to install .NET Framework 3.5 as it needs new compiler.

Also Following should be taken care while converting.

• If we are doing this conversion in Vista we need to open VS2008 as an Administrator.
• If an application includes controls or extenders from the ASP.NET AJAX Control Toolkit, while upgrading to the latest version of the .NET Framework. we must upgrade to a new version of the toolkit in order to run with the .NET Framework 3.5.
• If existing environment includes a source-control system, all necessary files will be automatically checked out by the conversion wizard. The conversion will fail if a file cannot be exclusively checked out.
• A project must be closed and reopened after its target .NET version has been changed.


I have tried converting few sample projects and I have not faced any issues.

Submit this story to DotNetKicks

 

Latest Articles