Just jQuery The Core UI - Forms
Written by Ian Elliot   
Friday, 17 March 2023
Article Index
Just jQuery The Core UI - Forms
HTML 5 Input
Form Events And Validation
Hand Coded

Hand Coded

Normally when the submit event is triggered the browser handles converting the form elements into a query string or post data. However, it is possible to take this over and do the job in code. All the browser does is to take the name/value attributes of each of the input elements within the form and convert them to a query string or post data.

There are two functions which you can use to convert the data into something you can transfer to the server or just use internally:

  • .serialize() converts the form data to a query string suitable for including in a get request

  • .serializeArray() converts the data to an array of JSON coded strings.

JSON is useful if you want to send the data using Ajax or if you just want to use the data internally. 

The serialize function returns a query string containing the data from the form that you pass it or any form elements that you pass it.  Unless you want to modify or make use of the query string in an Ajax get you might as well let the browser do the job in response to a submit event.

For example, you can convert the form given in the earlier example to a query string using:

var queryString = $("#form1").serialize(); 
alert(queryString);

The resulting queryString is:

username=test&
password=abcd&
maths=on&
group1=option2&
description=%20%20Text%20area%0D%0A%20%20%20%20%20%20&
dropdown=Option2

There are a few things to note. The first is that the password is transmitted in the clear as part of the query string. The second is that the query string is URL encoded, for example the spaces have been converted to %20. Finally, the more complex elements such as the radio buttons have been processed and only the selected element is included. 

If you want to send the data using Ajax then what you need is most probably a JSON coding of the data.

The serializeArray function will convert a collection of forms and form controls to an array. Each array element is a single object with a name and a value property, {name:"name",value:"value"} for each of the form elements. 

While you can convert ad-hoc elements and multiple forms into a JSON string, the most common thing is to convert a single form. Any disabled controls, submit buttons and file select elements are not serialized into the string. Obviously all of the elements processed have to have sensible name attributes. 

The example form can be converted to JSON string using:

var json = $("#form1").serializeArray(); 
var jsonString= JSON.stringify(json);

The first instruction gets the array of objects and the second uses the built in JSON object to convert this to a JSON string. The result is:

[{"name":"username","value":"test"},
 {"name":"password","value":"abcd"},
 {"name":"maths","value":"on"},
 {"name":"group1","value":"option2"},
 {"name":"description","value":" Text area\r\n "},
 {"name":"dropdown","value":"Option2"}]

You can see that the results are the same, but the way they are represented has changed. 

If you want a single object with properties corresponding to the name and value pairs then it is easy enough to convert the array into a single object:

var json = $("#form1").serializeArray();
var jsonObject={};
var i;
for(i=0;i<json.length;i++){
 jsonObject[json[i]["name"]]=json[i]["value"];
}

You can also convert this to a JSON string:

var jsonString= JSON.stringify(jsonObject);

which produces:

{"username":"test",
 "password":"abcd",
 "maths":"on",
 "group1":"option2",
 "description":"Text area\r\n",
 "dropdown":"Option2"}

You can use this object to access the form data more directly. For example, you can use it to validate the data using instructions like: 

if( /[0-9]/.test(jsonObject.username)){
  alert("a user name cannot contain digits");
}

The is also a $.param() function that takes an array, object or jQuery object and converts it to a URL query string. This is used internally by jQuery to implement serialization. 

The Future Of Forms 

HTML5 introduced many new features for forms. As well as more specific input types, it also introduced automatic validation and many other ways to specify what is a legal input. It might seem that the days of writing JavaScript to do the job of client side validation are over. However, while HTML5 helps with the problem, it doesn't eliminate it all together. Code can be much more flexible and sophisticated. It can tell the user at a much earlier stage that there is something wrong with the input and it can perform validation checks that work with multiple fields for consistency. jQuery and JavaScript still provide ways of doing the job that are not browser specific. 

Summary

  • The main purpose of a <form> tag is to specify what is to happen to the data collected by the controls it contains. It does this using two attributes - action and method. The action attribute specifies the URL where the data will be sent and the method is usually either post or get and specifies how the data is sent to the server. 

  • There are a number of ways of triggering a submit event but the most common is to include a submit button within the form.

  • Get and post are two HTTP methods which send data back to the server and get the next web page.

  • The biggest simplification is that jQuery provides an extended set of selectors to find standard form elements. 

  • The submit function can be used to trigger a submit event on a form element or assign an event handler which is called before the form processes the data. 

  • You can check for valid data in a form using a regular expression that the field corresponding to name has to satisfy to be valid.

  • There are a set of events that you can use to control what happens when the focus shifts to all elements: focus, blur, focusin and focusout.

  • The serialize functions can be used to convert the data in the form into a string.

 

 

 

More Information

http://jquery.com/

jquerysq

 Available as a Book:

smallcoverjQuery

buy from Amazon

  1. Understanding jQuery
  2. Basic jQuery CSS Selectors
       Extract: The DOM
  3. More Selectors
       Extract: Basic Selectors
  4. The JQuery Object
  5. Filters 
  6. DOM Traversal Filters 
  7. Modifying DOM Objects
       Extract: Modifying The DOM 
  8. Creating Objects & Modifying The DOM Hierarchy
  9. Working With Data
       Extract: Data ***NEW!!!
  10. Forms 
  11. Function Queues
  12. Animation 
  13. jQuery UI
  14. jQuery UI Custom Control
  15. Easy Plugins 
  16. Testing With QUnit
  17. Epilog A Bonus Function

Also Available:

jquery2cover

buy from Amazon

 

To be informed about new articles on I Programmer, sign up for our weekly newsletter, subscribe to the RSS feed and follow us on Twitter, Facebook or Linkedin.

 

raspberry pi books

 

Comments




or email your comment to: comments@i-programmer.info

<ASIN:1871962501>

<ASIN:1871962528>

<ASIN:1871962560>



Last Updated ( Friday, 17 March 2023 )