Training Guide: Programming in HTML5 with JavaScript and CSS3 Ebook

(Nora) #1

Lesson 1: Understanding forms CHAPTER 7 321


The QueryString is a list of name value pairs that are URI encoded. Spaces become plus
signs (+), the apostrophe becomes %27, and the exclamation point becomes %21. The separa-
tor between each name and value is the equal sign (=), whereas the separator between each
name value pair is the ampersand (&).

Quick check
■■How can you use the URL to send data to the server?

Quick check answer
■■Add a question mark (?) to the URL after the webpage name and then include
the QueryString.

Serializing the form


If you want to create the same string of URI-encoded name value pairs to use in your code,
you can use the jQuery serialize method. This method converts the form data to a URI-
encoded list of name value pairs. This could be useful when you want to post data program-
matically to the server. The serialize method looks like this.
var formData = $('#myForm').serialize();

If you are working with the URI-encoded data and you want to decode the data, you can
use either the decodeURI function to decode a complete URI or the decodeURIComponent
function to decode a QueryString. For example, you can use the following code sample to
serialize the form data and then decode the data.
var formData = $('#myForm').serialize();
var data = decodeURIComponent(formData);

Using the autofocus attribute


When an HTML form is displayed, the default focus behavior is that no control has focus. In
the past, developers have added JavaScript to set the focus to a specific control when the
page is loaded and ready. The following is an example of using jQuery to set the focus to the
text box whose name attribute is comment.
$(document).ready(function () {
$('input[name="comment"]').focus();
});

HTML5 introduces the autofocus attribute to form controls. The autofocus attribute is a
Boolean attribute and can be set for the comment as follows.
<input type="text" name="comment" autofocus="autofocus"/>
Free download pdf