Archive for 23rd March 2008

Editing Text On Click With JavaScript / DOM

Recently asked in Yahoo! Answers:

Clickable text to edit? Javascript?
So I saw somewhere on this website that they had rows of DYNAMIC data that when you clicked on the actual text (onfocus), the text would turn into a editable text field containing the text, and then when you clicked off of it (onblur?), AJAX was used to update the database that the data came from with that new changed value. I believe it was used to edit categories on the fly.

How do I do this? I can figure out the AJAX/PHP/Mysql part, but I really suck at javascript. I just need to be able to have some text turn into a text field when clicked that contains that text for editing. I’m sure you understand.

Thanks so much.

This is actually pretty straightforward. Basically, you do it with two DIVs: one contains the text you want to make editable, the other contains a textarea that will edit the text. Clicking on the text DIV makes the edit DIV visible; submitting the edits changes the text and hides the edit form.

But, like all things that seem simple, there are a couple of small adjustments we need to make to ensure our solution both works as intended and is safe from HTML injection.

Let’s get to it. As always, a working demo / code you can download appears at the end of this entry.

Continue reading ‘Editing Text On Click With JavaScript / DOM’ »