Reputation: 3782
What I am making is basically is a user profile that has a text box for description added by the user about himself/herself. Although I have a separate page where the user can edit the profile, but I want to provide a feature that when a user hovers over his description box then he sees an edit
button.
If the user clicks that button, then he/she can edit the description field there itself, and the backend will be updated using Ajax. The ajax call and the backend processing is simple, but how can I replace the html
with a textarea
and submit
button and again put back the original html using javascript.
Here is what my html look like
<div id="personalText" >
<a href="#" id="editButton"> edit </a>
<p id="descText">{{profile.desc}}</p>
</div>
When somebody clicks editButton
I want to replace the html inside personalText
with a textarea
containing the original text in descText
, and an update
button. And when the user edits the text and click update, I will update the backend model and again put the <a>
tag and the <p>
tag.
Can anybody help. I seem to know how to do parts of it, but can't figure out how I will replace the original structure on update
click.
Upvotes: 0
Views: 1064
Reputation: 40863
Instead of creating/destroying DOM elements an option would be to have the edit <textarea/>
hidden.
<div id="personalText" >
<div class="display">
<a href="#" id="editButton">edit</a>
<p id="descText">{{profile.desc}}</p>
</div>
<div class="edit" style="display:none;">
<input type="submit" value="Update"/>
<textarea>{{profile.desc}}</textarea>
</div>
</div>
Then your jQuery can simply toggle the elements and handle your ajax post.
$("input[type='submit']").on("click", function() {
$.ajax({
url:"/your/url/"
}).success(function(){
$(".display, .edit").toggle();
$("#descText").html($("textarea").val());
});
return false;
});
Upvotes: 2
Reputation: 14944
$('#editButton').click(function(){
var text = $('descText').text();
var textArea = $('<textarea></textarea>');
textArea.value = text;
$('#personalText').replaceWith(textArea);
});
Upvotes: 1