Sometimes it is nice to be able to edit a page without displaying form elements by default. For example, if you want to allow people who are logged in as administrators to edit sections of a page, you could make it so that the administrator could click on those sections to turn them into form elements.
To view the demo, first:
- From the command line (on a PC) or terminal (on a Mac), navigate to the directory MoreAjaxApplications/Demos/.
- Type npm install to load the required Node.js modules.
- Type npm start to start the server.
- Open http://localhost:8080/Presidents in a browser to view the page
Our example below shows a simple table showing the presidents' first and last names:
The neat thing about this table is that the names become editable when double clicked:
All the user has to do is type a new value and tab out or click anywhere else in the document to change the value in the table. An XMLHttpRequest is used to change the record in the database.
This page is generated by the Node.js response route /Presidents in MoreAjaxApps/Demos/server.js and rendered by the MoreAjaxApps/Demos/Presidents.jade template. The server-side code queries the "Presidents" database to retrieve a list of all presidents' IDs, first and last names, and bios, and returns those data as an HTML table.
The code queries the database for the presidents' first and last names and biographies (taken from the ) and then iterates through the result set creating a table row for each president. Each td element has the editable class.
The Jade template includes a call to MoreAjaxApps/Demos/inline-editing.js, which does the real work:
HTML5 includes a contenteditable attribute that can be applied to almost any element, though Internet Explorer does not allow it on elements that make up tables (e.g, table, tr, td, etc.). Editing contenteditable content in the browser can be tricky/quirky when nested tags are involved, but it is pretty simple (and cool) when you are dealing with straight text.
To run the demo, first start the Node.js server if it isn't already running: navigate from the command line/terminal to MoreAjaxApps/Demos/ and type npm start. Then browse to http://localhost:8080/contenteditable.html.
The code is simple:
Although contenteditable wasn't added to the specification until HTML5, it is well supported by browsers in use today - even Internet Explorer 6.
Of course, when the user changes content on the page that doesn't have any permanent effect. You, as the developer, have to catch that change and do something about it. When a editable element loses focus, a blur event is triggered (there is no change event). You can use the blur event to trigger Ajax code that saves any changes the user made. Run the following example to see how it works: