Reputation: 5580
I'm trying to use Jquery (with no plugins) to enable an edit in place control. The functionality I would like is this. On click of paragraph, the paragraph will be converted into an editable text area. Once the user clicks out paragraph (loses focus) the text will be saved.
I have the following code below and currently part 1 is working, but when I click in the editable area textarea rows="10" cols="160 gets generated and I can't type. Here is what I have
$("#Para1").click(function () {
var textarea = '<div><textarea rows="10" cols="160">' + $(this).html() + '</textarea>';
$(this).html(textarea);
$("textarea.textarea").focus();
$("textarea.textarea").blur(function () {
var value = $(this).val();
$("#Para1").text(value);
});
I have tried to base my code per the link below, but haven't had success.
Upvotes: 2
Views: 1701
Reputation: 7021
I would solve this using 2 html elements, that are shown/hidden when necessary:
<div id="Para1">blabla</div>
<textarea id="editable" style="display:none" rows="10" cols="160"></textarea>
Then use the following Javascript:
$("#Para1").click(function () {
$('#editable').html($(this).html()).show().focus();
$(this).hide();
});
$("#editable").blur(function () {
$('#Para1').html($(this).val()).show();
$('#editable').hide();
});
EDIT: moved the click handler on '#editable' outside of the '#Para1' click handler. No need to hook it up multiple times. Updated fiddle here.
An example JsFiddle can be found here.
Upvotes: 1
Reputation: 8954
Try this
http://jsbin.com/UmelOku/1/edit?html,js,output
Here is the code JS:
$("#Para1").click(function () {
$(this).css('display','none');
$('textarea').css('display', 'block');
$('textarea').val($(this).text());
$('textarea').focus();
});
$('textarea').blur(function () {
var value = $(this).val();
$("#Para1").text(value);
$(this).css('display','none');
$('#Para1').css('display', 'block');
});
HTML:
<p id="Para1">Test</p>
<textarea style="display:none;" rows="10" cols="160"></textarea>
Upvotes: 1
Reputation: 12717
$("#Para1").click(function () {
var textarea = '<div><textarea class="editable" rows="10" cols="160">' + $(this).html() + '</textarea>';
$(this).html(textarea);
$("textarea.editable").focus();
$("textarea.editable").blur(function () {
var value = $(this).val();
$("#Para1").html(value);
});
});
You don't have class assigned to your textarea in your generated html. But, you are referencing it by the class .textarea. I added a class of editable and changed your reference to textarea.editable.
Upvotes: 1