University of Bridgeport



jQuery

jQuery syntax appears as:

$(selector).action()

e.g., $("body").css({'backgroundColor':'red','color':'green'});

jQuery element selectors allow you to select elements (or groups of elements) by id, tag name, attribute name, or by content. Selectors allow you to manipulate HTML elements as a group, or as a single element.

Values that are not numbers or booleans or nulls should be surrounded by quotes e.g.,

$("body").css({'backgroundColor':'#ffffa0','color':'green'});

Selectors can be the element type, id of a particular element or the css class e.g.,

$(“p”).hide() // hide all p tags

$(“#p1”).hide() // hide the element with id=p1

$(“.mypara”).hide() // hide all elements with class = mypara

$(“p.mypara”).hide() // hide all paragraph i.e., p elements with class = mypara

$(“p#mp”).hide() // hide first paragraph with id = mp

$(this).hide() // hide the current element

Selectors can indicate multiple selections or parent child relationships as:

|div, p |The comma (,) operator means AND. All divs and paragraphs on the page will be selected. |

|div > p |The greater than (>) operator means direct child of. Any paragraphs directly inside of any divs are |

| |selected |

|div p |The space ( ) operator means any child of. Any paragraphs inside a div are selected, even if they are |

| |inside of other elements within the div. |

Example 1:

Test of JQuery

function changePara()

{

// basic jquery syntax $(selector).action()

// you can chain many actions

// no quotes around mypara, or use "#mypara"

$(mypara).css("border","1px solid red").css("backgroundColor","yellow");

// both backgroundColor and background-color are

// acceptable in above css call

}

This is a test of jquery

Apply jquery style to it

[pic]

Example 2: $(“document”).ready, adding removing styles, mouse over, and mouse out events.

$(“document”).ready guarantees that all the components of the page have been loaded by the browser. It is a good place to attach event handlers and to add, remove styles.

Test of JQuery

$("document").ready(function() { // like body onload

$("body").css({'backgroundColor':'rgb(255,255,180)','color':'green'});

$(btnTest).click(function() {

$("p.mainHeading").hide();

//$(mypara).css("background-color","red");}); // one paragraph

$("p").css("background-color","red"); // all paragraphs

$(rnews).removeClass('blueYellowStyle');

$(rnews).addClass('redYellowStyle');

});

$(btnTest2).click(function() { $(rnews).removeClass('redYellowStyle');

$(rnews).addClass('blueYellowStyle');});

$(mypara).mouseover(function() { $(this).css("background-color",'rgb(200,200,255)');});

$(mypara).mouseout(function() { $(this).css("background-color","white");});

$("li.first").mouseover(function() {$(this).removeClass('blueYellowStyle').removeClass('mainHeading');

$(this).addClass('redYellowStyle');});

$("li.first").mouseout(function() {$(this).removeClass('redYellowStyle');

$(this).addClass('blueYellowStyle').addClass('mainHeading');});

});

.mainHeading

{

font-size:14pt;

color:blue;

background-color:yellow;

}

.redYellowStyle

{

color : red;

background-color:yellow;

}

.blueYellowStyle

{

color : blue;

background-color:yellow;

}

.greenYellowStyle

{

color : green;

background-color:yellow;

}

This is a test of jquery

Apply jquery style to it

This is second paragraph

First Item in the List

Second Item in the List

Third Item in the List

Recent News for XYZ Corporation

[pic]

Example 3: Mouse move event and page and client coordinates.

Test of JQuery

$("document").ready(function() { // like body onload

$("body").css({'backgroundColor':'#ffffa0','color':'#f00000'});

$(testm).mousemove(function(e) { var out1 = e.clientX + ":" + e.clientY;

$("#mp").css({'left':e.clientX,'top':e.clientY,'width':50,'height':20});

$("#mp").html(out1);

}); //pageX, pageY for page coordinates

$(testm).click(function(e) {alert(e.clientX + ":" + e.clientY)});

});

.mainHeading

{

font-size:14pt;

color:blue;

background-color:yellow;

}

This is a test of jquery

test area for mouse move

[pic]

Example 4: jQuery uses Xpath like syntax for selecting elements. There are some minor differences in XPath as used in XML versus XPath in jQuery. The use of @ for selecting attributes has been deprecated in jQuery. For example to select a paragraph with id of “mypara”,

$(‘html/body/p[@id=”mypara”]) will be written as:

$(‘html>body>p[id=”mypara”])

The above raises the question of how to select the text inside a paragraph. For this jQuery uses the text() action as demonstrated by the following example.

Test of JQuery

function changeParaViaXPath()

{

$("div[id='mypara'] #subpara").css("border","1px solid red").css("backgroundColor","yellow");

// select id=subpara inside a div with id=mypara

// space can be used in jQuery instead of a / in XPath

// can also use $("div#mypara p#subpara")

// $("div[id='mypara'] p") will select all p inside mypara

// $("div[id='mypara'] p[id='subpara']")

}

function changeParaViaXPath2()

{

$('html>body>div>p[id=subpara]').css("border","1px solid red").css("backgroundColor","yellow");

// $('div>p[id=subpara]') // means any level in XPath

// $('div>p[id*="sub"]') * means anywhere in id

// $('div>p[id^="sub"]') ^ means starts with

// $('div>p[id$="bpara"]') $ means ends with

}

function searchParaViaXPath()

{

var ptext = $('div>p[id="subpara"]').text();

// .text() action returns the text content of an element

var psel = $('div>p[id="subpara"]')

if (ptext.indexOf("inside") >= 0)

psel.css("border","1px solid red").css("backgroundColor","green");

}

jquery selection via XPath

jQuery uses XPath to select an element.

inside

[pic]

Examples of jQuery Selectors:

$("*") - selects all elements

$(this) - selects the current element

$("h2.mainHeading") - selects all elements that have a css class of mainHeading

$("div:first") - selects the first element

$("ul li:first") - selects the first element of first element

$("ul li:first-child") - selects the first element of every element

$("[href]") - selects all elements with an href attribute

$("a[target='_blank']") - selects all elements with a target attribute value equal to "_blank"

$("a[target!='_blank']") - selects all elements with a target attribute value not equal to "_blank"

$(":button") - selects all elements and elements of type="button"

$("tr:even") - selects all even elements Try it

$("tr:odd") - selects all odd elements

$("div[class]").hide() - hide all divs that contain a class attribute

$("p:eq(0)").show() - show the first paragraph on the page

eq(i) acts like an indexer

$("p:visible").hide(); - hide all paragraphs that are currently visible

$("ul/li") - get all li elements that are part of a ul:

$("p.mypara[img]") - get all paragraphs, with a class of 'mypara', that have an image in them:

$("li[a:contains('shop')]") - get list item that contains link with "shop" text inside

$("input[name=txtUsername]").val(); - read text from txtUsername input field.

// Note that val( ) action is used for input fields instead of text()

$("input[type=radio][checked]") - all checked radio buttons

Processing Forms Using JQuery:

Web Adder

$("document").ready(function() {

$('#btnAdd').css({'background-color':'red'});

//$('input[name="btnAdd"]').css({'background-color':'red'}); // also ok to select using name

$('#btnAdd').click(doAdd); // like delegate

});

function doAdd()

{

var n1 = parseFloat($('#txtN1').val());

if (isNaN(n1))

{

alert('invalid first number');

$('#txtRes').val("");

$('#txtN1').focus();

return;

}

var n2 = parseFloat($('#txtN2').val());

if (isNaN(n2))

{

alert('invalid second number');

$('#txtRes').val("");

$('#txtN2').focus();

return;

}

$('#btnAdd').css({'background-color':'yellow'});

var res = n1 + n2;

$('#txtRes').val(res);

}

Simple Web Adder

First Number :

Second Number:

------------

Result :

[pic]

CheckBoxes with JQuery:

Check if the checkbox is checked

There are several ways to get to work out if a checkbox is checked or not with jQuery, and here a couple of alternatives. Each will return true if it's checked or false if it's not.

1. $('input[name=foo]').is(':checked')

2. $('input[name=foo]').attr('checked')

Set the checkbox to checked or not checked

The status of the checkbox can be changed using the attr() function like so, to check the box:

$('input[name=foo]').attr('checked', true);

and like so to uncheck the box:

$('input[name=foo]').attr('checked', false);

RadioButtons with JQuery:

Radio Buttons Processing via JQuery

$("document").ready(

function() {

$('#btnSubmit').click(processForm);

});

function processForm()

{

radChecked = $("input[name='rating']:checked").val();

var txtFeedback = $("#txaComments").val();

var email = $("#txtEmail").val();

var checkedChoices = new Array();

$("input[type='checkbox']:checked").each(function(i) {

checkedChoices.push($(this).val());

});

alert("You selected \n" + radChecked + "\n" +

"Your Expertise : " + checkedChoices.toString() + “\n” +

txtFeedback + "\n Your email: " +

email);

}

Site Feedback

Please provide your comments about our new site.

E-mail Address:

Rating:

Excellent

Very Good

Good

Fair

Poor

Your Expertise:

Programming

Web Development

General Comments:

[pic]

[pic]

jQuery load to obtain data from a page in synchronous manner:

Create an aspx page called “JqueryTestLoad1.aspx” with the following html.

$("document").ready(function() { // like body onload

$('#btnGetInfo').click(function(e) {

//alert("hello");

$('#wout').load("GetTime.aspx",

{ CNM: $("#txtCompany").val(), CID: 1234 });

});

});

Symbol :

The above jQuery code submits the data for two fields called CNM and CID to a page called GetTime.aspx. The response from GetTime.aspx is brought back and displayed in the div with an id of wout.

The GetTime.asp page has no html. The server side code is shown below.

public partial class GetTime : System.Web.UI.Page

{

protected void Page_Load(object sender, EventArgs e)

{

string nm = Request["CNM"];

string id = Request["CID"];

if (id == "1234")

Thread.Sleep(4000);

Response.Write("Time on Server = " +

DateTime.Now.ToString() +

"" + "Caller Name = " + nm + " Caller ID=" +

id);

}

}

[pic]

JSON Serialization and JSON Response:

Create an aspx page called JQueryTestJSON.aspx with the following code.

$("document").ready(function() { // like body onload

$('#btnGetInfo').click(function(e) {

alert("hello");

$.getJSON("GetTimeJSON.aspx",

{ CNM: $("#txtCompany").val(), CID: 1234 },

function(res) {

$('#wout').text(res.Time + "" + res.Message) ;

//$('#wout').html(res.Time + "" + res.Message);

});

});

});

Symbol :

The above page triggers a page called “GetTimeJSON.aspx”, so we need to add this page with the following code (server-side code only).

using System.Web.Script.Serialization;

public partial class GetTimeJSON : System.Web.UI.Page

{

protected void Page_Load(object sender, EventArgs e)

{

string nm = Request["CNM"];

string id = Request["CID"];

if (id == "1234")

Thread.Sleep(4000);

JSONInfo jsi = new JSONInfo();

jsi.Time = "Server Time = " + DateTime.Now.ToString() ;

jsi.Message = "" + "Caller Name = " + nm + " Caller ID=" +

id;

JavaScriptSerializer js = new JavaScriptSerializer();

string resp = js.Serialize(jsi);

Response.ContentType = "application/json";

Response.Write(resp);

Response.End();

}

}

Add a class called JSONInfo to the app_code folder with the following code:

public class JSONInfo

{

public JSONInfo()

{

}

public string Time { get; set; }

public string Message { get; set; }

}

[pic]

................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download