Form elements
With jQuery Mobile, native form elements are all converted into custom controls when the browser supports it. These custom controls are enhanced versions of native form elements as well as a few special form elements specifically created by the framework. Fortunately, all the form elements downgrade for browsers that do not support them, so usability is not a concern. Text inputs with jQuery Mobile are essentially the same as native text inputs; however, you can use new HTML5 input types such as email
, tel
, and number
. To create any of these form elements, you simply need to set the input type to one of those mentioned values. For a complete list of HTML5 input types, see Resources.
In addition to the supported HTML5 input types, you can create a slider. A slider includes a handle and a gutter upon which the handle slides. The value of the slider is stored as the handle is moved, and that value is then submitted when the form is submitted. To create a slider, you start with a basic HTML input, but you define the type
attribute as range
. Then, you add min
, max
, and value
attributes and define a default value for the value
attribute, which determines where the handle will be positioned on the slider. Listing 14 shows an example of a slider element with a max
value of 10
, a min
value of 0
, and a default value
of 2
.
<div data-role="fieldcontain"> <label for="slider">My slider:</label> <input type="range" name="slider" id="slider" value="2" min="0" max="10" /> </div>
The last custom input type is a flip toggle switch, which is already common on mobile devices. It’s a great element to handle on/off or true/false types of data. There are multiple ways that users can work with the flip switch—by taping one side or the other of the switch or by dragging the flip handle like a slider. Creating a toggle switch is similar to creating a slider, although there are a few big differences. The input becomes a select
element, and two options are added. Listing 15 provides an example of a toggle switch that could be used to provide on/off functionality.
<div data-role="fieldcontain"> <label for="slider">Select slider:</label> <select name="slider" id="slider" data-role="slider"> <option value="off">Off</option> <option value="on">On</option> </select> </div>
You probably also noticed that there is a data-role
attribute with a value of slider
. This attribute value converts a custom jQuery mobile select list into a toggle switch.
Conclusion
The jQuery Mobile framework provides a quick solution to creating usable UI components for mobile websites. In most cases, with just a few simple lines of HTML you can include a mobile UI component that adds value to your mobile website. The complete list of components that the framework provides isn’t covered in this article, but to learn more about the framework components and see them in action, check out the links in Resources.