View Full Version : Function to edit a <p> tag

03-24-2009, 02:03 PM
I have a form when submitted the values are captured on a PHP file. I have added the function below to edit the values. The function works but when you save the file are re-open the changes have not been saved. Is there any chance this can be done in JavaScript without server side scripts?

var editing = false;

if (document.getElementById && document.createElement) {
var butt = document.createElement('BUTTON');
var buttext = document.createTextNode('Save!');
butt.onclick = saveEdit;

function catchIt(e) {
if (editing) return;
if (!document.getElementById || !document.createElement) return;
if (!e) var obj = window.event.srcElement;
else var obj = e.target;
while (obj.nodeType != 1) {
obj = obj.parentNode;
if (obj.tagName == 'TEXTAREA' || obj.tagName == 'A') return;
while (obj.nodeName != 'P' && obj.nodeName != 'HTML') {
obj = obj.parentNode;
if (obj.nodeName == 'HTML') return;
var x = obj.innerHTML;
var y = document.createElement('TEXTAREA');
var z = obj.parentNode;
y.value = x;
editing = true;

function saveEdit() {
var area = document.getElementsByTagName('TEXTAREA')[0];
var y = document.createElement('P');
var z = area.parentNode;
y.innerHTML = area.value;
editing = false;
document.onclick = catchIt;

03-24-2009, 04:06 PM
You could use cookies, but those aren't great for storing anything important, because the expire and people can delete them and the client can change them. I actually have no idea what you asking but I hope this helps anyway. Also, what does this have to do with a P tag?

03-24-2009, 04:25 PM
The function I posted edits <p> tag.

Can you give me a simple example of using a cookie for my problem please?

03-24-2009, 06:51 PM
Ok, first of all, your code only seems to work in IE. Unless this is for personal use, this really wont work. Second, it seems very roundabout, and I don't even see what you trying to do. Explain, please. From what I can see, you have a textbox. Pressing a button destroys the button and the textbox, and creates a P with the textbox's content. Then if you click on the page again it goes back to the textbox and button. If this is really what is happening, why do you expect it so save it in between refreshes? I'm rather confused.

03-25-2009, 09:33 AM
Didn't realise the code only works in IE (that's not a problem though).

What the code allows me to do is edit the value captured from a textbox. The file the values are displayed is a PHP file. The value is wrapped in a <p>.

<strong>Details: </strong><p><?php echo $_POST["details"]; ?></p><br />

When you click on the text it changes to a textbox (which you can edit). Next to the textbox is a button which allows you to save your changes (which it does). However when I save the page and then re-open it the changes are lost. If there anyway I can keep the changes. As I have mentioned before I am not sure if this is possible.

thanks for your help.