dcsimg

JQuery Mobile, Part 3: Attack of the Forms

Need to capture some data from you users? jQuery Mobile forms differ from traditional forms in a couple of ways but can save you some headaches when building your app.

Collecting data

In our prior articles we have introduced JQuery Mobile and begun to look at application structure. In this article we continue our look at JQuery Mobile by touching upon forms handling.

While many mobile applications are dominated by the presentation of information, we cannot escape the fact that mobile devices are ideally suited for data gathering, or data-collection.

In addition to fun things like capturing images and GPS coordinates with our mobile devices, sometimes we simply need to ask the user to enter in some information the old fashioned way — via a form.

Forms have been around since the beginning of time, it seems.

Forms for JQuery Mobile are both the “same”, and “different”, from traditional HTML-coded forms.

First, the similarities:

  • You use the familiar <form method=”post” action=”someaction”> </form> syntax.
  • You provide a name attribute for each element of your form.
  • When the form is submitted, the data is submitted as expected to the “action” of the form.
  • You can setup an “onsubmit” handler to pre-process a form submission.

JQuery Mobile forms differ in a few important ways from traditional HTML forms.

The Document Object Model (DOM) is leveraged by JQuery Mobile to build a more seamless, single-page navigation experience. This approach is implemented by having the DOM manage multiple pages simultaneously rather than recreating it on each page load. A consequence of this approach is that the “id” attribute must be unique across all form elements, not just unique within a single “html” page. As your application moves from page to page, the DOM is expanded, making subsequent transitions via JavaScript/DOM magic rather than asking the browser to fetch the HTML again and reparsing the contents into a new DOM.

For example, consider how many times in your JavaScript coding you have used something like:

var theField = document.getElementById('firstname');

or in JQuery syntax:

var theField = $('firstname');

Imagine if you had a field named “firstname” on more than one page of your web application, not an unreasonable expectation in many applications that handle people’s names and relationships. In JQueryMobile we need to make sure that these id attributes are unique across all pages to avoid confusion over which element is to be manipulated via JavaScript.

Adopting a naming convention would be a good idea as you set out to construct JQuery Mobile applications. Something along the lines of pagename-fieldid would provide a reasonable namespace moat to reduce the chances for clashing id values.

JQuery Mobile also makes some decisions for us when it comes time to perform the layout of a form, depending on the screen dimensions of the device. Think about it, a mobile device can readily be rotated. Users now expect applications to happily handle those rotation scenarios and react in an intuitive manner. Doing this with traditional SDK development approaches requires some particular attention to implement these features. JQuery Mobile handles these events by providing a dynamic form layout process, using the available width for forms and stacking the form “labels” when the width is insufficient to have them directly to the left of a related field.

See the image below showing an iPhone (browser powered by WebKit) displaying a simple form.

Simple form running in WebKit on iPhone
Simple form running in WebKit on iPhone

When the image is rotated it happily switches around the labels to handle the available real estate.

Rotated form
Rotated form

Here is the code for this simple form.

<!DOCTYPE html>
<html>
<head>
<title>Linux Mag JQuery Mobile Sample Form</title>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.0a2/jquery.mobile-1.0a2.min.css" />
<script src="http://code.jquery.com/jquery-1.4.4.min.js"></script>
<script src="http://code.jquery.com/mobile/1.0a2/jquery.mobile-1.0a2.min.js"></script>
</head>
<body>
<div data-role="page" id="page1">
	<div data-role="header">
		<h1>Header goes here</h1>
	</div>
	<div data-role="content">
		<form method="post" rel="external" action="http://www.postbin.org/lvxp2b">
		<fieldset>
		<legend>Personal Information</legend>
		<div data-role="fieldcontain">
			<label for="firstname">First Name</label>
			<input type="text" name="firstname"><br/>
		</div>
		<div data-role="fieldcontain">
			<label for="lastname">Last Name</label>
			<input type="text" name="lastname">
		</div>
		</fieldset>
		<button type="submit" value="Save">Save Data</button>
		</form>
	</div>
	<div data-role="footer">
		Footer, Copyright, etc.
	</div>
</div>
</body>
</html>

Some items to note about this code sample:

  • JQuery Mobile script and css includes.
  • data-role attributes delineate the page, header, content, and footer sections.
  • The form tag’s attributes are no different than a traditional HTML page you’ve seen for years.
  • The fieldset tag element marks out the set of fields for the form, including the legend element which provides a heading for the collection of fields.
  • The data-role attribute of fieldcontain delineates the individual fields.
  • The use of the label tag associated with its respective input element allows labels and input fields to be rendered together in an appropriate fashion.
  • There is not a bit of code or text dedicated to rotation-specific handling, yet the application handles rotation quite readily.

Regarding other form elements beyond labels and text elements, JQuery Mobile provides stylized versions of these as well. Rather than enumerating all of them here, have a look at the reference provided on the JQuery Mobile website. These elements not only look a bit different from basic HTML form elements, but they are also controlled by JQuery Mobile’s theming capabilities. The net result is that we have a powerful means of controlling the look and feel of the application. This is something that web developers have learned to expect from JQuery over the years.

That wraps up our introduction to JQuery Mobile forms. Next time we’ll have a look at handling events with JQuery Mobile.

Comments on "JQuery Mobile, Part 3: Attack of the Forms"

tpp

The example of var theField = $("firstname"); is missing a pound sign. It should be var theField = $("#firstname"); See the id selector documentation here: http://jquerymobile.com/demos/1.0a2/#experiments/api-viewer/docs/id-selector/index.html

Also, the input filed with a name id attribute of “firstname” should have an attribute of “firstname” because we are using getElementById("<id>")

<input name="firstname" id="firstname" type="text"/>

Reply
wstidolph

Short-term warning: the alpha2 dist of jqm doesn’t work with SELECT “multiple” … this requires jqm version a3pre. This confused me, because the jqm online docs are published from the head of the tree (the /test subdir at github) while the CDN distribution links are for alpha2.

Another notable characteristic of the jqm approach is that it rewrites your page somewhat, and this can interact poorly with other dynamic page-generation libraries (e.g., using ‘knockout’ to dynamically generate <OPTION> elements results in OPTIONS which are not visible on the jqm-styled page).

Reply

Thanks for sharing, this is a fantastic article. Really Cool.

Reply

Hey very nice blog!! Man .. Beautiful .. Amazing .. I’ll bookmark your blog and take the feeds also‚ĶI am happy to find so many useful information here in the post, we need work out more techniques in this regard, thanks for sharing. . . . . .

Reply

Haha, shouldn’t you be charging for that kind of kned?ewgol!

Reply

Heya i am for the first time here. I came across this board and I find It truly useful & it helped me out a lot. I hope to give soehnmitg back and help others like you helped me. http://bdhtmhsmmd.com [url=http://piirbni.com]piirbni[/url] [link=http://xzmnnsnb.com]xzmnnsnb[/link]

Reply

revenues become http://carinsurancerut.info like everyone here http://carinsuranceast.us law bit http://safeinauto.com insurance company insurance providers http://autoinsuranceweb.top money provide http://autoinsurancemaw.info quotes score back http://autoinsurancersr.top work dastardly act http://cheapautoinsurancewcx.info specific injured http://carinsurancequotessc.top best suits

Reply

indeed help http://cheapcarinsurancefc.top car damage http://carscoverageonline.com companies offer select http://carinsurancemr.net mobile recovery reduce http://autoinsurancend.info grade average alcohol limit http://carinsurancequotessc.top ask last few http://cheapcarinsurancecr.top earn discounts easily accomplished http://cheapautoinsurancewcx.info pay encourages safer http://autoinsurancequotesro.info couple

Reply

minimums http://cheapcarinsurancefc.top include comprehensive http://autoinsurancequotesem.us study found involved http://safeinauto.com numerous medical coverage http://carinsurancert.top should insurance http://autoinsuranceweb.top just having good http://autoinsurancemaw.info discount two variations http://cheapcarinsurancecr.top undermine policies http://autoinsurancenir.top company

Reply

more time http://autoinsurancemaw.info best estimated market http://autoinsurancequotesem.us quotes sites would http://autoinsuranceweb.top greatly considered problems encourages http://cheapcarinsurancecr.top sports

Reply

relevant websites http://autoinsurancequotesem.us company related uninitiated http://carinsurancerut.info insurance cheap licensed http://carscoverageonline.com however

Reply

tax see http://autoinsurancegl.net companies risks http://carinsurancelit.top other driver insurance company http://autoinsurancebit.net encounter any sort http://autoinsurancemaw.info substantially restrict meant http://autoinsurancequotesro.info someone

Reply

find yourself http://carinsurancemr.net now low-priced http://autoinsurancersr.top against competitors competitive car http://autoinsurancebit.net quote lowest http://cheapcarinsurancefc.top same-sex couples

Reply

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>