My goal is to enable users to edit the text within a paragraph on a website. I am attempting to replace the <p>
tags with <textarea>
tags using the .replaceWith()
function. However, when I try to retrieve the value of the textarea
, it comes back as blank. Here's a link to the JSfiddle.
Here is the HTML code:
<p><a class="edit">Edit</a>I'm going to change this into a textarea field and retrieve the value.</p>
This is the JS code:
$(document).ready(function() {
$('.edit').hide();
var object = $('p');
object.on("mouseenter", function() {
$('.edit').show();
object.on('click','.edit',function(){
var oldText = object.text();
oldText = oldText.substr(4); // Exclude the word 'Edit'
object.replaceWith($("<textarea>").val(oldText).css("width",object.css('width')).css('height',object.css('height')));
var value = object.val();
alert("Value: "+value);
});
});
});
As a beginner in programming, any tips on style or implementation are appreciated. This solution is just my initial attempt at solving the issue, there may be a more straightforward way to achieve the same outcome.
EDIT: I should note that in my website, each paragraph is sourced from a database table and displayed through an AJAX function. Upon completion of editing, the user can click a button to update the table by taking the new value from the textarea
field and executing
UPDATE *table* SET *text*=newText WHERE *text* LIKE oldText;