jQuery Mobile Framework – A Forms Tutorial

jQuery Mobile Framework – A Forms Tutorial

Tutorial Details
  • Technology: jQuery Mobile
  • Difficulty: Intermediate
  • Estimated Completion Time: 2 hours

jQuery Mobile is a relatively new mobile web framework, with its first release made in October 2010. The framework has many interesting features to support development of web based mobile applications. In this tutorial, we will focus on some basic elements of jQuery Mobile: page structure, forms and Ajax form submission. The tutorial is based on version 1.0 alpha release 2 of the jQuery Mobile framework.

As part of the tutorial we will write a small B2C application. A package shipment company has a form in their web site for customers to enter information on packages that are lost or damaged during shipment. Using a hand-held device (e.g. a web enabled phone) a customer inputs information to the form about their claim: the shipment number from the original receipt, name/address, and a description of loss/damage. When the customer submits the form, the web site responds with a claim id for further tracking. The scenario is shown in the diagram below:

Tutorial application context diagram

Figure 1. Tutorial application context diagram.

jQuery Mobile framework supports a variety of browsers including iOS devices, Android devices, Blackberry OS 6, and webOS (for a support matrix, see http://jquerymobile.com/gbs/). The application in this tutorial has been tested against an Android 2.2 device and an iOS 4.1 device.

Design Considerations

Before going into technical details, let us talk about main considerations driving the design of the application.

  • Short response time: It is preferred for the web application to contain a single html page with a simple user interface. All user interface constructs, such as error dialog and confirmation pages, will be part of the html page. Once the page is downloaded into the browser, different sections of the page will be shown to the user depending on the particular context. There will be no need to open multiple network connections to download pages several times.
  • Error handling: If the user forgets to enter a required field in the form, submission should fail with a warning dialog. Missing fields should be easy for the user to find.
  • Support for multiple devices/browsers: Applications should have consistent look-and-feel and behavior across supported devices and browsers.

Of course, a typical real-life application will have additional or different design concerns. For the purposes of this tutorial, our scope will be limited to the considerations above.

jQuery Mobile Introduction

Most of the discussion in this section has been borrowed from the documentation in http://jquerymobile.com. See the original reference for further details.

jQuery Mobile is a user interface system built on the popular JavaScript framework jQuery. It consists of user interface elements and programming constructs that provide consistent functionality across a large variety of mobile and desktop web browsers. The ‘Progressive Enhancement’ and ‘Graceful Degradation’ principles are behind its design. Core functionality of the framework supports a broad set of platforms whereas newer platforms benefit from more enhanced features.

jQuery Mobile has a relatively small footprint. Since basic configuration of a jQuery Mobile page is done purely by markup, it is possible to achieve quick development cycles, particularly if your application does not need complex programming functions. Although built on jQuery core, theming system of jQuery Mobile is based on a new CSS framework that aims to separate color and texture from structural styles that define things like padding and dimensions. An event handling API handles touch, mouse, and cursor focus-based user input methods in a unified manner.

jQuery Mobile comes out of the box with many user interface elements such as header and footer toolbars, buttons with icons, form elements (including touch sensitive slider and toggle switches) and lists. Basic HTML styles, two or three column grids, and collapsible elements are also provided.

Inclusion of jQuery Mobile Libraries

As of jQuery Mobile 1.0 alpha 2 release, the following stylesheet and JavaScript libraries must be included in your HTML pages. You can reference them as below or serve them from your own server:

<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>

Container and Content Pages

Let us introduce the basic structure of a page in jQuery Mobile. A page in jQuery Mobile framework can be a single page or a local internal linked ‘page’ within a page. A ‘container’ page will include one or more ‘content’ pages. The boundary of a container page is defined as follows:

<div data-role="page">
...
</div>

Observe that the value of the data-role attribute is page. On the other hand, the boundary of a content page is defined as follows:

<div data-role="content">
...
</div>

Observe that the value of the data-role attribute is content.

A content page may have an associated header and footer. As an example, a container page with several content pages may have the following structure:

<div data-role="page">
  <div data-role="header">...</div>
  <div id="contentWithHeaderAndFooter1" data-role="content">...</div>
  <div data-role="footer">...</div>
  <div data-role="header">...</div>
  <div id="contentWithHeaderAndFooter2" data-role="content">...</div>
  <div data-role="footer">...</div>
  <div id="contentWithNoHeaderAndFooter" data-role="content">...</div>
</div>

When a container page is loaded, all content pages in it will be visible. In our application, we need to display only one content at a time. Therefore, we need to programmatically control which content will be displayed depending on context.

Hiding/Showing Content Pages

In order to hide an element, use the jQuery Mobile API hide() function:

$('#hdrMain').hide();

will hide the header with id hdrMain. Here, we used the jQuery ID selector by passing id of the element we would like to select preceded by # sign. Conversely, the show() function shows a hidden element:

$('#hdrMain').show();

The hide() and show() functions apply to elements of many different types, in particular, <div> tags and anchors (<a> tags). In this tutorial, we will use hide() and show() functions extensively to display only the relevant context to the application user. More details are given below.


Step 1: Demo Application Page Structure

Our demo application consists of a single html page, index.html, which consists of a container page as shown below:

<div data-role="page" data-theme="b" id="page1">
  <!-- ====== main content starts here ===== -->
  <div data-role="header" id="hdrMain" name="hdrMain" data-nobackbtn="true">...</div>
  <div data-role="content" id="contentMain" name="contentMain">
    ...
  </div>
  <div data-role="footer" id="ftrMain" name="ftrMain"></div>
  <!-- ====== main content ends here ===== -->
  <!-- ====== dialog content starts here ===== -->
  <div align="CENTER" data-role="content" id="contentDialog" name="contentDialog">
    ...
  </div>
  <!-- ====== dialog content ends here ===== -->
  <!-- ====== transition content page starts here ===== -->
  <div data-role="content" id="contentTransition" name="contentTransition">
    ...
  </div>
  <!-- ====== transition content ends here ===== -->
  <!-- ====== confirmation content starts here ===== -->
  <div data-role="header"  id="hdrConfirmation" name="hdrConfirmation" data-nobackbtn="true">...</div>
  <div data-role="content" id="contentConfirmation" name="contentConfirmation" align="center">
    ...
  </div>
  <div data-role="footer" id="ftrConfirmation" name="ftrConfirmation"></div>
  <!-- ====== confirmation content ends here ===== -->
    ...
</div><!-- page1 -->
  • The main content contains the form to be filled out by the user and has both a header and a footer.
  • Dialog content is displayed only if a required form field is missing when form is submitted. It consists of a warning and an OK button to close the dialog. Observe that it does not have a header or footer.
  • Transition content is displayed after the form is submitted until the response is received from the server. It consists of a “spinner” image with short text informing the user that their form is being submitted. Transition content also does not have a header or footer.
  • Confirmation content is displayed a after response is received from the server. It displays the confirmation number to the user. Confirmation content has both a header and a footer.

Content transitions are shown in the diagram below:

Content transitions

Figure 2. Content transitions.

Additional observations on the code listing above:

  • The data-theme attribute allows us to choose from available styles in the jQuery Mobile framework: <div data-role="page" data-theme="b" id="page1">. The default theme has various color swatches named a, b, c, d, e, each providing a consistent set of colors for different elements in the page. For our application we chose the color corresponding to b.
  • Headers come with a back button. We did not need back buttons and therefore chose to hide them via data-nobackbtn="true".
  • It is possible to provide some text to be displayed in the footer between the <div> tags. In our application we omitted text in the footer. As a result, the user will see in the footer only a thin bar colored the same as the header. With text, the footer will have a similar height as the footer with the text in it.

Form Elements

Our claims form consists of the following fields:

  • Several input fields of type text: Shipping number, First name, Last name, Email, Phone, Street address, City and Postal code. All are required fields except Phone.
  • A select element for State. This is a required field.
  • A textarea element for a user to enter information regarding the missing or damaged shipment. This is a required field.

As an example, let us look at the text field for Shipping number:

<div id="shipDiv" data-role="fieldcontain">
  <label for="shipNo">Shipping number*</label>
  <input id="shipNo" name="shipNo_r" type="text" />
</div>

We used a label with a for attribute whose value is the same as the id of the input element the label is attached to. Furthermore, we wrapped the label and input in a div with data-role attribute valued as fieldcontain. jQuery Mobile framework will utilize the fieldcontain attribute value for special styling. In addition, look at name="shipNo_r". For this particular application, we decided to define the value of the name attribute of any required form element to be the value of the id attribute appended by _r. If the element is not required, the value of the name attribute will be the same as the value of the id attribute. For example, since Phone is not a required field, it is defined as follows:

<div id="phoneDiv" data-role="fieldcontain">
  <label for="phone">Phone</label>
  <input id="phone" name="phone" type="text"/>
</div>

As we will see later on, this special naming convention will help us detect missing fields during form submission.

Another notable form element is the select element. Similar to the above, the value of the for attribute is the same as the id of the select element the label is attached to. Also, the label and select are wrapped in a div with the data-role attribute value as the fieldcontain. With the long list of options that we have in this application, jQuery Mobile framework will open the list in a new page when the user focuses on the select element.

  <div id="stateDiv" data-role="fieldcontain">
    <label id="stateLabel" for="state">State*</label>
    <select id="state" name="state_r" tabindex="2">
      <option value="ZZ">Please select a state</option>
      <option value="AL">Alabama</option>
      <option value="AK">Alaska</option>
      <option value="AZ">Arizona</option>
      ...
    </select>
  </div>

The form page as displayed in an Android 2.2 phone is shown below. The user will scroll through the page to access the elements in the form:

Form page

Figure 3. Form page in an Android phone.

The same form is shown in an iPod touch running iOS 4.1:

Form page

Figure 4. Form page on an iPod touch.


Step 2: Variable Definitions

We will reference various elements in the html page throughout our code. It makes sense to define those references only once and reuse them as needed. For this reason, we declare globally used variables as well as constants in the head section of the page:

<script>
  // Global declarations - assignments made in $(document).ready() below
  var hdrMainvar = null;
  var contentMainVar = null;
  var ftrMainVar = null;
  var contentTransitionVar = null;
  var stateLabelVar = null;
  var whatLabelVar = null;
  var stateVar = null;
  var whatVar = null;
  var form1var = null;
  var confirmationVar = null;
  var contentDialogVar = null;
  var hdrConfirmationVar = null;
  var contentConfirmationVar = null;
  var ftrConfirmationVar = null;
  var inputMapVar = null;
  // Constants
  var MISSING = "missing";
  var EMPTY = "";
  var NO_STATE = "ZZ";
</script>

Assignments of those variables are done in jQuery $(document).ready() function using ID selectors, as shown below. (Recall that jQuery $(document).ready() function is called when the entire DOM hierarchy in the page is loaded. That function is the best location to initialize our variables.) We also define inputMapVar as a collection consisting of all input elements with _r in their name attribute (The function call $('input[name*="_r"]') selects all such elements).

<script>
  $(document).ready(function() {
    // Assign global variables
    hdrMainVar = $('#hdrMain');
    contentMainVar = $('#contentMain');
    ftrMainVar = $('#ftrMain');
    contentTransitionVar = $('#contentTransition');
    stateLabelVar = $('#stateLabel');
    whatLabelVar = $('#whatLabel');
    stateVar = $('#state');
    whatVar = $('#what');
    form1Var = $('#form1');
    confirmationVar = $('#confirmation');
    contentDialogVar = $('#contentDialog');
    hdrConfirmationVar = $('#hdrConfirmation');
    contentConfirmationVar = $('#contentConfirmation');
    ftrConfirmationVar = $('#ftrConfirmation');
    inputMapVar = $('input[name*="_r"]');
    ...
  });
  ...
</script>

Step 3: Content Selection Functions

Let us now look at the content selection functions that will be called by event handlers.

For hiding and displaying the Main content and its header/footer, we use the hideMain() and showMain() functions:

function hideMain(){
  hdrMainVar.hide();
  contentMainVar.hide();
  ftrMainVar.hide();
}
function showMain(){
  hdrMainVar.show();
  contentMainVar.show();
  ftrMainVar.show();
}

For hiding and displaying the transition content, we use the hideContentTransition() and showContentTransition() functions:

function hideContentTransition(){
  contentTransitionVar.hide();
}
function showContentTransition(){
  contentTransitionVar.show();
}

For hiding and displaying the Dialog content, we use the hideContentDialog() and showContentDialog() functions:

function hideContentDialog(){
  contentDialogVar.hide();
}
function showContentDialog(){
  contentDialogVar.show();
}

Finally, for hiding and displaying the confirmation content and its header/footer, we use the hideConfirmation() and showConfirmation() functions:

function hideConfirmation(){
  hdrConfirmationVar.hide();
  contentConfirmationVar.hide();
  ftrConfirmationVar.hide();
}
function showConfirmation(){
  hdrConfirmationVar.show();
  contentConfirmationVar.show();
  ftrConfirmationVar.show();
}

When the page is loaded, only the main content should be displayed. For this reason, other content pages are hidden:

<script>
  $(document).ready(function() {
    // Assign global variables
    ...
    hideContentDialog();
    hideContentTransition();
    hideConfirmation();
  });
  ...
</script>

We will discuss how to tie together those content selection functions with the event handlers below.


Step 4: Form Submission

When a user presses the submit button we need to validate the form data before actually submitting the form. To keep things simple, we will only check if all the required fields have been provided. If form validation is successful, we display the transition content which consists of a spinner image with a short text informing the user that their form is being submitted. If validation fails, we display the dialog content which consists of a warning and an OK button to close the dialog.

Form Validation

Labels of the form elements with missing data will be highlighted in red. For this purpose, we add a new style class named missing and extending the jQuery Mobile label class.

label.missing  {
  color:#FF0000;
  font-weight:bold;
}

Below is the event handler for form submission. In typical jQuery notation, the identifier for form1 is passed to the jQuery object call to handle the submit event:

$('#form1').submit(function() {
  var err = false;
  // Hide the Main content
  hideMain();
  // Reset the previously highlighted form elements
  stateLabelVar.removeClass(MISSING);
  whatLabelVar.removeClass(MISSING);
  inputMapVar.each(function(index){
    $(this).prev().removeClass(MISSING);
  });
  // Perform form validation
  inputMapVar.each(function(index){
    if($(this).val()==null || $(this).val()==EMPTY){
      $(this).prev().addClass(MISSING);
      err = true;
    }
  });
  if(stateVar.val()==NO_STATE){
    stateLabelVar.addClass(MISSING);
    err = true;
  }
  if(whatVar.val()==null||whatVar.val()==EMPTY){
    whatLabelVar.addClass(MISSING);
    err = true;
  }
  // If validation fails, show Dialog content
  if(err == true){
    showContentDialog();
    return false;
  }
  // If validation passes, show Transition content
  showContentTransition();
  // Submit the form
  $.post("/forms/requestProcessor.php", form1Var.serialize(), function(data){
    confirmationVar.text(data);
    hideContentTransition();
    showConfirmation();
  });
  return false;
});

We set an error flag to false and hide the main content that contains the form. We then reset the previously highlighted labels on each member of the collection inputMapVar. To do that, we pass an inline function as an argument to each() that simply contains $(this).prev().removeClass(MISSING);. Note that this is the selected input element and prev() returns its immediate previous sibling which is the label associated with it.

The state for state selection and what for claim description are not text fields. Therefore, the corresponding labels have their styles reset separately.

After all the previously highlighted labels are reset we revisit the required input elements to check if any of them has a missing value. If that is the case we add the missing class to the label associated with the input field:

  // Perform form validation
  inputMapVar.each(function(index){
    if($(this).val()==null || $(this).val()==EMPTY){
      $(this).prev().addClass(MISSING);
      err = true;
    }
  });
  if(stateVar.val()==NO_STATE){
    stateLabelVar.addClass(MISSING);
    err = true;
  }
  if(whatVar.val()==null||whatVar.val()==EMPTY){
    whatLabelVar.addClass(MISSING);
    err = true;
  }

In addition, the error flag is set to true and the error dialog is shown. The figure below shows the error dialog in our Android 2.2 phone:

Error dialog

Figure 5. Error dialog.

After the user presses the OK button, the user is displayed the form page with the missing fields highlighted, as shown below. In that picture, the orientation of phone screen is horizontal. Observe that each label and its sibling text field are displayed in a single line as opposed to the vertical orientation in Figure 3 where the label is above the text field.

Form page

Figure 6. Form page with a missing field highlighted.

On the other hand, if validation is successful we show the transition content and submit the form as discussed below.

Submitting the Form via Ajax

The form submission uses the jQuery Mobile post function that accepts three arguments:

$.post("/forms/requestProcessor.php", form1Var.serialize(), function(data){...});
  • The first argument is the server URL to submit the form to.
  • The second one is the form content to submit. To get the form content, we simply call serialize() on the jQuery object by passing it the identifier for our form.
  • The third argument is an in-line function to process the response, data, sent back from the server.

Note that the post function performs an Ajax call which is asynchronous by nature. Immediately after calling the post, program execution will continue by returning false from the submit function and user will start seeing the Transition content.

Transition

Figure 7. Transition page displayed during form processing.

The in-line function to process the response is executed only when the server returns its response. For simplicity, the server application processing the form data, requestProcessor.php, returns a hard-coded claim id for the user to use for future reference. Before sending the claim id requestProcessor.php, it sleeps 4 seconds to emulate server processing time. It is in this period that the application will display the Transition content.

<?php
usleep(4000000);
echo('FTREIK12345678');
?>

When the server response is received, the event handler code is executed. The first step is to populate the span tag named confirmation with the value returned from the server. This is simply done with:

confirmationVar.text(data);

Then, we hide the Transition content and show the Confirmation content that contains the span tag named confirmation:

<div data-role="content" id="contentConfirmation" name="contentConfirmation" align="center">
    <p>A new claim has been created based on data you have submitted.</p>
    <p>Your confirmation number is: <span id="confirmation" name="confirmation"></span>  </p>
</div>

The confirmation page displayed in our Android 2.2 phone is shown below (phone’s orientation is horizontal):

Confirmation

Figure 8. Confirmation page in Android 2.2.

The same confirmation page is displayed on an iPod touch as follows (orientation is vertical):

Confirmation

Figure 9. Confirmation page in iPod touch.


Deploying the Source Code

The source code for the tutorial has a simple folder structure. All resources are stored in a folder named forms. In that folder, there are two sub-folders, css and img. The css folder contains colors.css, which has the label.missing class, and img stores wait.gif, the spinner image. The index.html and requestProcessor.php files are directly under the forms folder. In our testing, we used an Apache web server with version 2.2.11 running PHP version 5.3.0. If you place the forms folder directly under the DocumentRoot of the web server, you can access the application via http://[your_host_name]/folder/index.html.


Conclusion

In this tutorial we introduced basic concepts from jQuery Mobile framework with focus on page structure, basic styling, form elements and Ajax form submission. A sample claims processing application was introduced to demonstrate those concepts. We provided screenshots of various pages of the application executing in an Android 2.2 phone and an iPod touch device with iOS 4.1. Some observations and closing remarks are given below:

  • Since jQuery Mobile is built on jQuery core, those who have prior knowledge of the jQuery framework could get up to speed with the jQuery Mobile framework easily.
  • The ability of the framework to represent multiple content pages in a single html page with built-in functions to show/hide those content pages appeared very convenient to create a form application with different views depending on state. For example, this technique can be applied to implement ‘wizard’ style user guides or multi-page survey forms.
  • Tested on desktop, Android 2.2, and iOS 4.1 platforms, both the look-and-feel and functional aspects of the sample application were consistent. During development, it should be possible to quickly test and debug the main aspects of a jQuery Mobile application in a desktop platform. Then, more testing can be done on the individual devices and browsers that the application is expected to support.

Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more
  • Tyler

    Funny, I just used jQuery mobile for the first time today to build an inventory management web app for our company. Integrated rather nicely with codeigniter to make building a rather useful app very quickly. Great tutorial, also…Looks like a nice way to work through a longer form when doing so on a phone.

    • http://simplegeeks.com Brian

      I just discovered and used jQuery Mobile yesterday for the first time also. I was building an inventory checksheet, which as you may guess, is a really long form. This tutorial brought a couple of ideas to my mind. Also, though, I think the best way to incorporate a long form is to use the “collapsible elements”.

  • dbrant

    Not sure it makes sense having a separate framework for mobile. JQuery is light enough and the ability to use JQUERY UI on a mobile device keeps a site in sync with the original non-mobile site by allowing reusage of code.

  • joshua drew

    I have been banging my head against my empty coffee cup on a jQuery Mobile + Form submission issue. In your example your relying on the user to navigate directly to your page or have a link that uses the rel=”external” attribute. The reason being is if you use the Ajax Linking this page blows up. Also even if you were not hiding any div’s and just doing a plain form post it still will not work. I cannot figure out how to get mywebsite.com/#/formpage/ to submit like mysite.com/formpage/. Any thoughts?

    • Randy

      This worked for me.

      “To prevent form submissions from being automatically handled with Ajax, add the data-ajax=”false” attribute to the form element.”

      http://jquerymobile.com/demos/1.0a4/docs/forms/forms-sample.html

    • http://www.debtadvice.co.uk Sarah Cowan

      Hi there,

      I think I’m all set up, but I’m having a similar issue to Joshua. When I navigate directly to the page it works a treat, but when I navigate from the site page to this page, where it introduces the #/ it’s not working. Any help here would be massively appreciated?

    • Steven Klein

      Did anybody find an answer about linking to this page with ajax? the document.ready function doesn’t load, you have to refresh the page. I’ve tried adding it to the page it links from but that hasn’t worked.

  • Kunal

    Why iOS for iPad or iPhone is avoided ? No tutorial for iOS on JQuery Mobile ?

    • rayshinn

      iPod Touch/iTouch/iPhone/iPad all runs iOS, so if it works on the iTouch like he tested on..why would it not work on the rest?

  • me

    minus

  • http://none Zakos

    Good , nice , I learned many new things from this , works great ( after a while……… )

    I’m using Spring 3 MVC + last Jquery Mobile libaries.

    Where are the documentation for the methods , like
    $(this).prev().removeClass(MISSING)
    $(this).val()
    $(this).val(“text”)
    etc…

    JQueryMobile Docs&Example dont cover all this.

    • MrBester

      JQM docs don’t cover basic functionality of jQuery; see api.jquery.com for .prev(), .removeClass(), val() etc.

  • http://none Zakos

    Is validation on the JSP is better then Server Validation?
    Cons? Pros? JSP faster and?
    When will we want to use each way?

  • Siby easow

    Thank you for writing this post. It was very helpful!

  • http://www.debtadvice.co.uk Sarah Cowan

    This is great. Just what I needed. Thank you. :)

  • Mark

    HI and thanks for this sample, being very new to this scene I wonder how do I actually send this (as a test) or a simple form to a specific email address, I see from your code this only return a confirmation number. any help?

  • http://ingehost.cl Ignacio

    Hi, im having trouble with this, im trying local and remote server and it keeps the transaction view with the img.gif spinning forever, never shows the confirmation screen, with the claim Number.

    thanks

    • Mu

      ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
      Having the same problem as Mark & Ignacio can we get some help on this Konur?

    • Mahsa

      I also have a same problem, any recommendations?
      Thanks for the very useful tutorial by the way :)

  • Todd

    I got it to work as downloaded, but when I try using the beta 1.0 framework it breaks- gets stuck on the fill out all fields message.

  • Ian

    I have the same problem as Todd, it does not work with the beta release, the form is not submitted! Anyone got any ideas how to get round this?

  • myshock

    Hello,
    I don’t want to troll about that but one thing is sure :
    For accessibility reasons, i suggest you to perform first à server side validation and then add extra js live validation features to give your app a trendy look ;-)
    Whenever jquery mobile has good accessibility features, this form would not be submited if js not activated. But this was not the goal of the tutorial.

  • http://delaportal.com Marc Jacobs

    I really enjoyed and learned a lot from this tutorial. Thanks a million for doing it. I do have one small question that I can’t figure out. After server submission and confirmation, you have a heading that says “Claim Created”. The top half never displays in the emulator on iPhone or iPad. It’s pushed up under the top bar with the clock, battery, etc. Any idea how to fix this?

  • http://www.nerdsonsite.ca/ James

    You have NO idea how little GOOD guides there are on jQuery and jQuery mobile. Thanks for being one of the good ones!

  • http://www.mobosurvey.com Tuan Bui

    Great article. If you want to see jquery mobile in action, check out http://www.mobosurvey.com we are using jquery mobile for our survey generator for mobile devices and it looks great.

  • Tuan

    Could you submit your source code ?

  • Mark

    Hi, can this example work on a test that i’m doing using jquery mobile / phonegap / xcode 4.1? all forms that I’ve tested are working on a desktop browser and android / iOs browesr but what about an OFFline form to be used in compile the web app into an app?

  • Frequent

    Nice tutorial. After setting it up myself, I found the download button :-D

    I was wondering how this would with all the message inside the actual page. Works nicely, but you will need to find workaround if you add headers in each message as JQM takes all header h1 and puts it into the page title. I’m ending up with “ContactMissing InformatioThank You For Your Message!”.

    Other than that. GREAT tutorial!

  • Frequent

    the tutorial is still using the old way of calling the loader. One reason you may get stuck. Try using:

    $.mobile.showPageLoadingMsg();

    and

    $.mobile.hidePageLoadingMsg();

    Cheers,

    Frequent

    • http://www.mcaldas.com Solum

      Hum… sorry, can you explain better where to add this code? I updated the JQuery and JQueryMobile JS libraries to the newest ones

      Cheers

  • http://www.infyways.com Mark Willam

    Awesome post
    Thank you for Sharing!

  • http://dianewestdesign.com Dennis West

    I am not getting an Confirmation echo back request from Processor.php.
    I am running on within visual studio web developer and submitting to a browser the form and all seems to work properly. would the problem be that the source code is .php and needs to be converted to .net. ?

    • http://myURL Nick

      In .NET, you would post to an .aspx page. To simulate what this article did, do something like this:

      protected page_load {
      Thread.Sleep(5000);
      Response.write(“FTREIK12345678″);
      }

      That’s just pseudo code, but you get the idea.

  • André

    Hello all,

    I hope you guys can help me out, I am a real dummy on programming jquery etc.

    So my goal is to make a form (already did) save the results on my tab, and whenever I have a connection sync it with my mysql database.

    Hope you can help me with this.

    Ragards,
    André

  • wjs

    Any idea on how to submit an image (file upload) as part of the form fields?

  • kleinS

    Has anyone been able to apply this to radio buttons? Can’t seem to get it to work, otherwise great tutorial!

  • jose

    I am completely new to jquery, jquerymobile BUT why are you using divs inside one pages instead of using multiple pages as suggested in the manual (http://jquerymobile.com/demos/1.0a4.1/docs/pages/docs-pages.html)?

    Thank you

    • http://kensleylewisproductions.com kensley

      …I think because this tutorial is outdated.

  • Jane B

    I think you have an error in your $.post statement:

    $.post(“/forms/requestProcessor.php”, form1Var.serialize(), function(data){

    The file requestProcessor.php is in the same directory as the index.html. Shouldn’t the line be:

    $.post(“requestProcessor.php”, form1Var.serialize(), function(data){

    When I used your example as downloaded, I got an exception and the ajax request failed.

    Thank you, whether I am correct or not, I really appreciated your tutorial. I understand jquery mobile much, much better.

  • james

    nice tutorial..thankyou

  • Stephen Brown

    Just a quick question the form you have on the page, does it have a form tag around it and if so does it have an action. I can only assume it does and that it will never be called due to the onSubmit always delivering a false. Would their be any circumstance where you would allow it to submit for example to change to another internal page. I tried this though and had trouble with detectibg submission on the new page. I wanted to un hide a logout button on every page but the only one it unhid it from was the current internal page. It might have been that I needed to do it using $().live(‘showpage’) or somthing for it to work and the page change interupted the process. More experimentation will probably be needed.

    • Tim

      I’m no expert, but I would think you would need to use sessions and have each page check to see if the user is logged in and show or hide the button accordingly.

  • Niels K

    Hello

    Just a question

    Where is the form you have submitted saved. and which file format will be saved form

  • http://gravatar.com/idmirsoft idmir

    Hola , primeramente agradecerle por el post, y de paso quiero hacerle unas consultas de jquery mobile.
    yo tengo mi index.htm que es la pagina 1.
    en el head de la primera pagina.

    //$( ‘#dvlogin’ ).live( ‘pageinit’,function(event){
    $(‘#dvlogin’).live( ‘pageinit’,function(event){
    $(‘#btninicio’).bind(‘click’, function(event, ui){
    $.mobile.changePage(“ui/Usuario.html”, {reloadPage : true,});
    });
    });

    y tambien tengo en la segunda pagina Usuario.html, en el head tengo este codigo
    $(‘#dvUsuario’).live( ‘pageinit’,function(event){
    $(‘#btnn’).bind(‘click’, function(event, ui){
    alert(‘Ingreso a la pagina 2′);
    });
    });

    En la pagina index.html el pageinit funciona de maravillas pero mi duda es de por que no se lanza el pageinit de la segunda pagina ya que no puedo enlazar los eventos de los botonos de la pagina 2 asi como lo hize en la primera pagina.
    Aclarando estoy trabajando con eclipse+phonegap jquery mobile +android
    por favor espero sus comentarios espero que me puedan ayudar, los agradecere.

  • http://Pocketsoft.co David

    Hi, I have created a simple HTML editor for mobile websites, with built in support for jquery mobile, please check it out at pocketsoft.co

  • Andrew

    Great tutorial! My only question is with regards to the form layout/styling of the example form. I am using Jquery-1.7.1 and Mobile 1.1.1 and the individual field “labels” do not have the same “column width” as shown in the example above (as you expand the window width). In fact, my input boxes creep in on the Labels as if there was no padding. Was this a CSS design or just a native feature of the version of Jquery + Mobile used? Any thoughts?

    Best regards!

  • Andrew

    UPDATE: After some slight “hackery”, aka copy and paste and cutting and examining, the key here is to include the [ for="name" ] in your label attributes!

    Thanks for a great tutorial!

  • Sidney Davis

    Can anyone assist with taking form information and placing onto/into an existing paper form?

    Thanks,

    Sid

  • sindhuri

    please anyone know how to pass error message dynamically in dialog page please send this code

  • Rory

    I’m having a problem with the actual confirmation coming up. I don’t believe the submission is being completed. I get the transition page saying “Your claim has been sent. Please Wait.” but it never shows the confirmation. I can manually go to the /requestProcessor.php page and see the echo statement, so I believe I have PHP set up and working properly.

    Any suggestions? FYI – I haven’t changed any of the code. I simply downloaded the zip and am trying to use the form as is.

  • Another stuck noobie

    Am I missing something? I downloaded the source files and opened the index page in my browser. When I click the submit button I get an error in the error console that reads: “TypeError: k.attr is not a function” and lists a link: “http://code.jquery.com/mobile/1.0a2/jquery.mobile-1.0a2.min.js. Also, I do not get an error on the page if I submit without filling out the required fields.

  • Fawad Ghafoor

    what is the purpose of and also $.post(“/forms/requestProcessor.php”, form1Var.serialize(), function(data){});

  • Rob Ganly

    Hi All, For those having problems with the confirmation page never loading (where it just keeps getting stuck on the spinning gif) you need to change line 252 of index.html.

    The form in the source code is submitting to ‘/forms/requestProcessor.php’ but in fact the index.html file is already in the forms folder so you just need to change this line to ‘requestProcessor.php’ and it will work.

    Rob Ganly

    • Momo

      thxxxxxxxxxxxxxxxxxxxx :))))