Quantcast
Channel: TechNet Technology News
Viewing all articles
Browse latest Browse all 13502

Introduction to jQuery for App Customization (Kevin Mehlhaff)

$
0
0

JQuery is a popular JavaScript library that is used by many websites. LightSwitch employs jQuery to make it easy for developers to customize their applications. JQuery enables you to easily select, manipulate, and traverse HTML elements in the document object model, or DOM. You can think of the DOM as being a tree of elements, with children, ancestors, and siblings. Traditional DOM manipulation with JavaScript is cumbersome and does not lend itself well to rapid application development. In addition, browsers have different quirks and not all methods work in all browsers. JQuery solves this by providing an easy-to-use programming model that works in any modern browser. By becoming familiar with jQuery and using it within a LightSwitch app, a developer can quickly create customizations and add additional functionality to their app.

How to Use JQuery

JQuery is exposed to programmers either via the jQuery function or a shortcut, $. You can create a jQuery object by passing in a selector or a DOM element as the argument to $().

For example, to select all the paragraph elements with a class of quote that are descendants of the element that has an id of main:

var $quotes = $("#main p.quote");

Then, $quotes is an object referencing the matching nodes. It is customary to store jQuery objects in variables beginning with $. This one line of code replaces several lines of code that would be necessary if you were to use the built-in methods of the JavaScript language. There are quite a few different JQuery selectors. Here’s a brief list:

Selector

Description

Example

(element)

Selects all elements with the given tag name

$(“div”)

(“#id”)

Selects a single element with the given id attribute.

$(“#main”)

(“.class”)

Selects all elements with the given class.

$(“.read-only”)

(“ancestor descendant”)

Selects all elements that are descendants of the given ancestor.

$(“div p”)

(“selector1, selector2, …, selectorN”)

Selects the union of the specified selectors.

$(“div, p, a”)

It is important to note that these selectors can be combined. In the example above, specifying “p.quote” gave only p elements that had the class quote.  This was then passed this as the descendent in an (“ancestor descendant”) selector.

JQuery provides several different methods you can call to manipulate a set of nodes contained within a jQuery object. Going back to the previous example, you can set the text in each matched paragraph to be italic by using the CSS method:

var $quotes = $("#main p.quote"); $quotes.css("font-style”, “italic");

Of course one-line is also possible:

$("#main p.quote").css("font-style", "italic");

Here are some common jQuery object methods:

Method

Description

Example

.find(selector)

Get the descendants of each element in the current set of matched elements, filtered by a selector

$(“p”).find(“span”);

.append(content)

Insert content to the end of each element in the set of matched elements.

$(“#main”).append(“

Title of Page

”)

.appendTo(target)

Insert every element in the set of matched elements to the end of the target.

$newJQueryObject

.appendTo(“#main”)

.css(propertyName, value)

Set a CSS property for each element in the set of matched elements.

$(“p.warning”).css(“color”, “yellow”)

.remove()

Remove the set of matched elements from the DOM.

$(“.error-message”).remove()

.next()/.prev()

Get the immediately following/preceding sibling of each element in the set of matched elements.

$(“#main”).next()

.after(content)/.before(content)

Insert content after/before each element in the set of matched elements

$(“.special”).after(“

You have won!

”)

.text(textString)

Get the combined text contents of each element in the set of matched elements. Or sets the text contents to be textString.

$(“.demo”).text()

.on(event, handler)

Attach an event handler function for one or more events to the selected elements

$(“th”).on(click, function(){

alert(“You clicked on a table header!”); })

.attr(attributeName, value)

Sets the value of the attribute for every matched element.

$(“input”).attr(“type”, “text”)

Note that most parameters that are content can be either HTML in a string, a DOM element, an array of DOM elements, or a jQuery object. For a full understanding of these methods, consult the JQuery API documentation.

It is important to differentiate between object methods, methods that you can call on objects created with $(), and core utility methods, methods that are called in the $.fn namespace and don’t operate directly on a jQuery object. Here are some examples of jQuery utility methods:

Method

Description

$.ajax(url, settings)

Perform an asynchronous HTTP (Ajax) request

$.each(collection, callback)

A generic iterator function to iterate over both arrays and objects.

$.inArray(value, array)

Search for value in array and return index if found or -1

JQuery Mobile

LightSwitch uses the jQuery Mobile user interface framework. JQuery Mobile is a JavaScript library that has an emphasis on making touch-friendly websites that work well on mobile devices such as smartphones and tablets.  It includes the principle of responsive web design which aims to make the layout of an app work well across many different device resolutions. One such example is the table control. When data is displayed in a table in a LightSwitch app, it uses the jQuery Mobile table control to automatically adjust its display based on the resolution of the device. Another benefit of this framework is that the LightSwitch app uses all of the jQuery Mobile CSS styles for the shell throughout. This makes it easy to theme an app with ThemeRoller. JQuery Mobile includes a lot of touch-friendly controls you can add to an app. For example, a slider control may be useful for allowing a user to pick among a range of values.  LightSwitch also uses the library for its single-page navigation model.

Using JQuery in LightSwitch

A LightSwitch HTML client application provides several entry-points in which to write client-side JavaScript code. One such entry point is that of a custom control. If the control type of an item on the screen is changed to be a custom control, render code can be written for it. The entry point will look something like this:

myapp.AddEditCustomer.FamilySize_render = function (element, contentItem) {// Write code here.};

Two parameters are passed to this render function. The first parameter, element, is the DOM element of the container in which the custom control should be rendered.  Since the element is a DOM element, you can wrap it in $() to create a jQuery object. The jQuery object methods can then be used to add additional DOM elements to this container. The second parameter, contentItem, is a JavaScript object that represents information about the item on the screen that should be rendered in this spot. The LightSwitch JavaScript API is used to write code against this contentItem.

Example

Let’s go over a simple example that will explain how to use jQuery to provide a better experience for someone using the app on a mobile device.

Create a new LightSwitch HTML client application. Add a new table called Customer and give it some fields as follows:

screen1

Add a Browse Screen for Customers. Then in the Command Bar for the screen, add a new button. Select the Customers.addAndEditNew method and create a new screen:

screen2

On the new Add/Edit screen we want to change how the user interacts with this field. Since the zip code will be a number we want the on-screen keyboard of the device the user is using to show only numbers. Select the Zip Code item and select “Edit PostRender Code” in the properties sheet:

screen3

The code-behind file opens up so we can write JavaScript. As you can see, we get a function with the familiar element and contentItem parameters. However, since this is a postRender function, element will contain the already rendered Age input textbox. Let’s write some code to see what element is and what it contains:

myapp.AddEditCustomer.Age_postRender = function (element, contentItem) {
    console.log(element.outerHTML);
};

Now F5 the app, click the Add Customer button, and examine the output in the Visual Studio Output window:

<div class="msls-clear msls-presenter-content msls-font-style-normal msls-vauto
    msls-hscroll"><input class="id-element" id="ab2e31e1a-Age" type="text" data-mini="true" />div>

So we know that we have a DIV element container with one child INPUT element. Let’s change the code now to modify this INPUT element:

myapp.AddEditCustomer.Age_postRender = function (element, contentItem) {
    $(element).find("input").attr("type", "number");
};

The JavaScript code we wrote first creates a jQuery object by passing the DOM element to the $() method. Then it calls the find object method to locate the input element. On that input element, we set the type attribute to number. This allows HTML5 devices to recognize that they should display a numerical keyboard when this field is being edited.

Now F5 the application, click the Add Customer button, hit F12 to start the Debugging Tools, and use the DOM Explorer in Internet Explorer to inspect the Age field on the page:

screen5

screen6

We see the following generated HTML:

<div class="msls-clear msls-presenter-content msls-font-style-normal msls-vauto
     msls-hscroll"><div class="ui-input-text ui-shadow-inset ui-corner-all ui-btn-shadow ui-body-a ui-mini"><input class="id-element ui-input-text ui-body-a" id="ab2e31e1a-Age" type="number"data-mini="true" />div>div>

The INPUT element was indeed modified to have a type of number. You might be wondering why an extra DIV was added to surround the INPUT element and why the INPUT element gained some new classes. This is because of jQuery Mobile’s processing. It adds additional elements and applies additional classes so that the INPUT field has the correct formatting.

Now when the user adds a customer and edits the zip code field on a mobile device, he or she gets the following number keyboard:

screen4

Next Steps

JQuery is a JavaScript library that makes it easy and fast to add, modify, and delete elements from a web page. If you’d like to learn more about jQuery, they have a great Learning Center you can check out. You can use jQuery in LightSwitch apps to provide additional functionality to your app whether that’s creating custom controls or modifying the behavior of existing controls. Stay tuned for future blog posts where we cover the LightSwitch JavaScript API and the promise programming construct for interacting with data from the middle tier.

- Kevin Mehlhaff, Software Development Engineer in Test, LightSwitch Team

Resources


Viewing all articles
Browse latest Browse all 13502

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>