Tuesday, May 22, 2012

JQuery Basics - Part II



JQuery Events

Jquery events have several methods which are used to execute a set of instructions when the user interacts with the web pages. We have Keyboard events (keypress, keyup, keydown), Mouse events (click, hover, double click,...) and Form events (submit, focus, blur,...). Event handlers are set of instructions will execute whenever state change occurs.

Usage

$('selector').events(function() {
// code...
});

Examples
1.  <div id='myid1'>Click me!</div>

$('#myid1').click(function() {
$('#'+this.id).html('Clicked');
});
 
2.  <input type='text' id='txt1' value='Enter value' > </input>

$('#txt1').focus(function() {
$(this).val('');
})
.keypress(function(event) {
if(event.which == '13')
alert('enter pressed');
})
.blur(function() {
alert($(this).val());
});

We can also apply event handlers using class attribute or by specifying the elements directly. For example

$('a').click(function(e) {
alert(this.id); });
});
will apply the routine to all anchor tag in the web page.

Apart from the above events, we also have methods like:
on(), off() to attach and de-attach event handlers from the elements
bind() to bind the event handlers
live() to attach event handlers to elements (both static and dynamic)


JQuery Ajax

Sunday, April 22, 2012

JQuery Basics


JQuery is one of widely used javascript library in the design and development of interactive web pages or applications. Using JQuery, we can implement the same functionality which are available in the vanilla js (pure js). Then, what makes JQuery famous and its wide acceptance among the developers. If you see the official website, you can find, "Write less, do more" & believe that this will be main reason behind its popularity. "Where we're writing less and where it is doing more", will popup in our mind after reading the above line. Here's the example to get and set values of a text element:

a) Get element value
var elementValue = document.getElementById('elementId').value; //pure js
var elementValue = $('#elementId').val(); //JQuery equivalent

b)Assign value to element
document.getElementById('elementId').value = '100'; //pure js
$('#elementId').val('100'); //JQuery equivalent

Quite simple, isn't. There're many more methods are available in jquery which will makes our work very simple. Before diving deeper, we need to know how to include the library into our web pages. There are two ways are available:
i) Download JQuery from official website.
ii) Include CDN links directly into web pages.


Simple JQuery Script
$(document).ready(function() {
alert('JQuery works');
});

The above script will display an alert while page load. $(document).ready() is the equivalent of windon.load() in pure javascript. It will execute the logic (which are written in its body) during page loading.

JQuery Selectors

Selector are statements used to select the elements based on the id, class, attributes and element itself.
$('#elementId);//selectors using element Id
$('.elementClass');//selectors using element class
$("element[attribute=value]");//selectors using attributes
$('element');//selectors using element Id

Apart from the above, the selectors allows us to perform condition operation while selecting elements. For example,
a) to select the elements having the name starts with 'ele', the selector will look like
$("element[name^='ele']");

b) to select the elements having the name contains 'col', the selector will look like
$("element[name*='col']");

Little caution need to be exercise while writing selector to select multiple elements. To learn more about selectors, please see the Selector Reference link.

JQuery Attributes

JQuery attributes are used to assign or remove attributes to the elements. The attributes such as val(), text(), html() are used to assign values or content to the elements, where as, attr() & removeAttr() used to assign values to the attributes or remove attribute from the elements. We also have methods which can deals with element's class attribute; they are addClass(), removeClass() and hasClass().

i) val(), text() & html() attributes
val() is used to get or set the values to input elements like text, textarea and select. The text() and html() are used to display or clear the content of elements such as label, div, paragraph. text() will display the content blindly whereas html() displays the formatted content.

ii) attr() & removeAttr()
To get or set the values of element attributes (like id, title, src), attr() is used, whereas removeAttr() is completely opposite.

iii) addClass(), removeClass() and hasClass()
As their name implies, these methods are used to add, remove or check the values of element's class attributes.

Attributes usage
var elementValue = $('#elementId').val();//gets the element value
$('#elementId').val(elementValue); //set the element value
var attrValue=$('#elementId').attr('attributeName');//get the attribute value
$('#elementId').attr('attributeName', 'attributeValue'); //set the attribute value

Examples on Selectors & Attributes
//Elements
<label id='lbl_text'></label>
<div id='html_attr' class='div_class' title='Sample title'></div>
<input type='text' id='txt' value='10/>

//Script
$('#lbl_text').text('text() attribute used to assign value');
$('#html_attr').html('html() attribute used to assign value');
$('#html_attr').attr('title', 'div element title changed using attr()');
if ($('#html_attr').hasClass('div_class'))
$('#html_attr').removeClass('div_class').addClass('new_div_class');
var txt_value=$('#txt').val(); //get text element value
$('#txt').val(parseInt(txt_value)+50); // assign value to text element

Watch out for the JQuery Basic - Part II in next post.
Comments, Suggestions & Questions are highly welcome.

About Knowledge Sharing

Am writing the blog (Knowledgesharingarticles) with the sole intention of sharing my knowledge which I have learned during the past seven years and happy to say that am still learning. Otherwise, survival won't be easy, especially in the Computer Science field. Started my career as Software Programmer Trainee after my diploma in 2005, later a year, I relieved from job and pursued my engineering degree (Information Technology, Anna University, Chennai) and currently working in an organization, handling projects in RTLS.

All the posting in my blog (except basics) deals with dynamic binding or on the fly creation of web application functionalities. Articles on Dot Net, JQuery, XML, XSLT, Databases and Android will be shared in the blog. I hope that the postings will help atleast few people.

திருக்குறள்
தொட்டனைத் தூறும் மணற்கேணி மாந்தர்க்குக்
கற்றனைத் தூறும் அறிவு

Thirukkural - Blind Translation (Transliteration)
Thottanaith Thoorum Manarkeni Maandharkkuk
Katranaith Thoorum Arivu

Thirukkural - Translation
In sandy soil, when deep you delve, you reach the springs below;
The more you learn, the freer streams of wisdom flow.


Comments are highly welcome. Happy learning....

Regards     
Nanda Kumar