# Create a Dynamic Content Editing System With jQuery UI

In this Nettuts+ tutorial, we are going to learn how to create a dynamic content editing system using the jQuery UI Widget Factory. We'll go over how to develop a logical, object orientated jQuery UI Widget, transform various nodes to editable text fields, delegate events within the widget framework, manage context, toggle icons, serialize data, and of course edit, restore and delete data using jQuery's fantastic AJAX functionality!

## Creating a Widget Blueprint

• #### Edit:

The url string used when editing content.

• #### Remove:

The url string used when deleting content.

As default values, we'll use javascript's location.href property which is the url of the current page:

• #### The Save Icon

If the save icon was clicked, we'll need to serialize our inputs, as we did above, using the _serialize method. Then, we'll need to call our widget's post method in order to submit the AJAX request to the server.

As such, we'll define two variables here, inputs and data. inputs will be defined as the jQuery collection of inputs within the context of this element and data will be the return value from the _encode method, just as above.

Finally, we'll call the _post method with it's three arguments, the serialized data, the type of post we're making (in this case, "save") and i which is used in the $.ajax success callback to update the appropriate elements in the DOM. • #### The Cancel Icon Finally, if the cancel icon has been clicked, we'll restore the icons and editable content back to their default states. To do this, we'll first call the _showIconSet method with two arguments, i and default. i will be used to select the appropriate collection from our _icons array and default specifies which icon set to show. Next, we'll chain the _transformElements method to this expression with one argument, i, which, as usual, is used to select the appropriate collection from our _editable array. Note: If you're not exactly sure as to what's going on in the methods we're calling, it's ok. We haven't defined these methods yet so there's no reason you really should understand yet. Hang tight, we'll be defining these methods shortly. • #### The Full Switch Statement ## That's It for the Click! Here's how the complete _clickHandler method looks now that we've defined it: ## Toggling the Icons To and Fro! In our event handler, we call the _showIconSet method whenever we need to toggle icon state between editor and default. This is the method responsible for making those changes. ## The _showIconSet method, step by step! Taking advantage of jQuery's awesome chaining capability, let's take a look at how we can change icon state with just one variable and statement! • #### Var Titles First off, were going to define a new variable, titles as an array, using a ternary operator. This variable will contain the title attributes for our icons. We'll check the iconSet argument to determine which icons we're displaying and the populate the array with the appropriate titles accordingly. • #### this._icons[i] Now, using i we'll select the appropriate element collection from our _icons array. • #### Eq(0) The eq method is used as a filter against a jQuery collection in that it returns the element with the specified index. Thus, calling eq(0)in the context of _icons[i] method will narrow our selection down to the icon with an index of 0 within that collection. In other words, the first icon. For more information on jQuery's eq method check the jQuery API • #### toggleClass() Using jQuery's toggleClass method, we'll add and remove classes to our icons, respectively. So, if a specified class is present, it will be removed. Conversely, if a specified class is not present, it will be added. We'll concatenate the appropriate classes for each icon with a space as the toggleClass method accepts multiple class names as a space separated list. Pretty nifty! Documentation for jQuery's toggleClass method can be found in the jQuery API • #### Attr('title', Titles[0]) With our first icon's classes now set, we'll define it's title attribute using the jQuery attr method. We'll set the title using the appropriate value stored in the title array we created just a moment ago. The array keys for the title array match the index of the icon currently selected so the title for this icon is available as titles[0]. To read up on jQuery's attr method, check the jQuery API • #### End() jQuery's end method is used to remove the most recent filter applied to a collection. By calling end here, we'll be removing the eq filter from our collection. In other words, we'll be working with _icons[i] again. Documentation for jQuery's end method can be found in the jQuery API • #### ... the Next Verse Same as the First! We'll use jQuery's eq method again to specify the second icon now. The second icon will have an index of one, since indicies are zero based, and as such we'll use eq(1) to select it. Following suite with the above expression, we'll us the exact same methods for the second icon as we did for the first but with the appropriate class names and title. • #### Return This The last thing we'll do here is return this so as not to break this methods chainability. ## Voilà! Now that we've defined our variable and expression, let's take look at the entire _showIconSet method now: ## _transformElements: The workhorse method! In this method, we'll be looping through the editable content in order to get / set an appropriate text / html string for that element relative to the type of transformation we're making. Then, we'll simply set the element's html. After the loop, as usual, we'll return this! ## Arguments This method takes two arguments, i and type. i, will be used to select the appropriate jQuery collection from the _editable array relative to _iconContainer[i] from the _create method. The type argument simply specifies the type of transformation that's being called. This method handles three three types of "transformation": • Making content editable and storing current values for possible retrieval • Restoring editable content back to its default state with it's original values • Restoring editable content back to its default state with new values As such, type will either be "edit", "restore" or "update". ## A Necessary Shortcut... First off, we'll need to define a variable which references the options.fieldNames array. It's necessary to define this reference within the context of this method so that it will be available to the inner function,$.each, we'll be calling shortly.

The fieldNames var will only be used when making elements editable.

## Iterating Through Our Editable Content

Using jQuery's $.each method, we'll iterate through _editable[i]. We'll pass the empty argument, index, to$.each. The numeric index of each element in the loop will be assigned to this argument.

## Variables Within the $.each Method Within the scope of$.each, we'll define / initialize two more variables respectively:

• #### Defining the html string

Lastly, we'll define the html var as a string representation of an input element. This string will be used to both create and inject this element with just one call to jQuery's html method.

We'll set the name attribute of this input by concatenating the appropriate value from the fieldNames array into the html string. This is where we'll use the index argument as it represents the index of the current element in the loop. So, if were working with _editable[0] the appropriate field name should be stored in fieldNames[0]!

In like manner, we'll the concatenate val into the string as the input's value attribute.

• #### Case "Restore":

If type evaluates to restore, we'll only need to retrieve the text for this element.

• #### Getting the Inputs Value

Using jQuery's attr method. we'll define the html var as the value attribute of the input.

• #### Setting the Default:

We'll have the switch default to return in the case that the type argument somehow doesn't evaluate to one of the appropriate strings.

#### The entire switch statement

With all of our cases defined, here's a look at the entire switch statement

## Setting the HTML

Using jQuery's html method, we'll now set the string we've defined as the html for this element.

## Arguments

This method takes one argument, inputs, which represents a jQuery collection of the elements we want to serialize.

## Serializing Inputs, the Easy Way!

Using jQuery's is method, which returns a boolean, we'll check the inputs argument against an "input" selector. If we are dealing with inputs, is will return true and as such, we'll then call jQuery's serialize method on this collection. serialize takes a form or a collection of inputs and returns a url encoded string of key / value pairs.

documentation for jQuery's serialize method can also be found in the jQuery API

## Serializing Everything Else!

If the inputs collection is not comprised of input elements, we'll build an object literal comprised of key value pairs representing, sort of, pseudo name and value attributes.

Once we've created this object, we can pass it to jQuery's $.param as an argument.$.param will serialize an array or object and return the url encoded string not unlike the jQuery serialize method.

• #### Initializing an Empty Object

Let's initialize the variable data an empty object. We'll populate this object in a moment as we iterate through our inputs.

• #### Caching this

First, let's cache the jQuery selector for this, the current element in our loop.

• #### Defining the key

The variable key will represent the name attribute for this element. The value of key is stored in the fieldNames array and it's index within that array is equal to the index of the current element in our loop. Thus, fieldNames[index]should contain the appropriate field name for inputs[index].

• #### Fetching the value

Lastly, we define the variable val as a sort of pseudo value attribute. We'll use jQuery's text method to get the text of the current element in the loop.

• #### Building the data object

With our key / value pairs defined, we'll begin populating the object using square bracket / associative array notation. We'll set the key for each item as key and the value as val. The benefit of using this type of notation, in this particular context, is that we can set the key with a variable. In literal notation, the variable key would be interpreted as the string "key".

• #### Returning the Encoded Data

Now that our iteration is complete and the data object is populated, we'll call jQuery's $.param method with data as its argument.$.param will return a url encoded string representation of the object or array passed to it.

For more information on the jQuery \$.param method check the jQuery API.

## The full _serialize method

Here's a look at the complete _serialize method: