I am attempting to create a script that allows the user to click a div
element with an h1
'd bit of text and then replace the h1
with a textbox and a graphic to click after editing. Once the graphic is clicked, the div
will replace the textbox and graphic with the newly edited h1
'd bit of text.
Here are the functions:
function savename() {
var s = $('#mytextbox').val();
$('#mydiv').replaceWith('<div id="mydiv" onclick="editname();"><h1>' + s + '</h1></div>');
}
function editname() {
var strName = $('#mydiv').text();
$('#mydiv').replaceWith($('<div id="mydiv"><input id="mytextbox" name="mytextbox" type="text" value="' + strName + '"><img id="mysavebutton" src="images/save.gif" onclick="savename();"></div>'));
}
And here is the div:
<div id="mydiv" onclick="editname();"><h1>Some text I want to edit</h1></div>
So, the div
click function works fine. It replaces the h1
element with a textbox. And when I click the save graphic, that works fine too, in that it returns the h1
. The problem is, the value of the textbox is supposed to be the h1
'd text. That part's not working. It still retains the old value. I put an alert for "s" after setting it to .val()
and it still shows the old value, even after editing. I feel like I'm missing something simple, but I've fought with it all day and need some fresh eyes to look at it for me. Thanks in advance.
Instead of replacing the mydiv and trying to re-creating mydiv, why don't you just hide mydiv on click and change the value of the h1 tag when you try to save?
In the html you can have something like this:
<div id="mydiv">
<h1 id="myoutput" onclick="editname();"> ... </h1>
<input id="mytextbox" name="mytextbox" type="text" style="display:none;">
<img id="mysavebutton" src="images/save.gif" onclick="savename();" style="display:none" />
</div>
Then in javascript:
function editname()
{
var s = $('#myoutput').text();
$('#myoutput').css('display', 'none');
$('#mytextbox').val(s).css('display','inline');
$('#mysavebutton').css('display', 'inline');
}
function savename()
{
var s = $('#mytextbox').val();
$('#myoutput').text(s).css('display', 'inline');
$('#mytextbox').css('display', 'none');
$('#mysavebutton').css('display', 'none');
}