Sunday 15 September 2013

jQuery - preserve html elements after change

jQuery - preserve html elements after change

I'm using Ruby on Rails to implement a simple edit/submit button to
replace the content of h4 that has class named "special-content".
Here is my code for rhtml:
<div class="modal-body" style="height: 280px !important;">
<%= image_tag("special/turkey.png", :alt => "turkey", :class =>
"special-img") %><br>
<h4 class="special-content">#93 Turkey, Avocado &
Cheese</h4><h4>&nbsp;with Small Sized Drink & Chip</h4>
</div>
and here is my code for jQuery, which is implemented right above the rhtml
code:
<script type="text/javascript">
$(document).ready(function() {
$("body").on("click", "#edit", function() {
$('#edit').replaceWith('<a class="btn" id="submit">Submit</a>');
$('.special-content').replaceWith('<input class="special-content-edit"
type="text" value="' + $('.special-content').html() + '">');
$('.special-img').replaceWith('<input class="special-img-edit"
type="text" value="' + $('.special-img').attr('src') + '">');
});
$("body").on("click", "#submit", function() {
$('#submit').replaceWith('<a class="btn" id="edit">Edit</a>');
$('.special-img-edit').replaceWith('<img class="special-img" src="' +
$('.special-img- edit').val() + '">');
$('.special-content-edit').replaceWith('<h4 class="special-content">'
+ $('.special-content-edit').val() + '</h4>');
});
});
</script>
The jQuery should allow users to replace the h4 content. Everything works
fine. However, if I navigate to another link and come back to the page,
the h4 content changes back to the original content ("#93 Turkey, Avocado
& Cheese"). How can I preserve the changed element?

No comments:

Post a Comment