Question

<div>
    <div class="first">First Name</div>
    <div class="last">Last Name</div>


    <div class="edit">edit</div>
</div>

When pressing edit, I would like the content inside .first and .last to be replaced with a textbox with the content of the div inside the textbox. Essentially, making the content noticeably editable.

I was able to achieve that with replaceWith.

However, if they click "edit" and then want to cancel, I need the textbox's to disappear and the original content show back up. I realized replaceWith would ruin the existing structure.

I had the idea of using clone, but I'm not sure if that is efficient.

What would be the best way to approach this with jQuery?

I found this how to make jquery-ui.dialog revert a form on cancel which seemed to do something similar to what I needed but I wasn't able to find anything in it that would help do what I wish.

Thanks so much, and I look forward to a reply!

Jacob

Was it helpful?

Solution

Here's a fiddle: http://jsfiddle.net/manishie/pZHMN/

It could use some refactoring, but it does what you want. Basically you save the original value as a data attribute of the enclosing div. If a user saves, you save the new value. If a user cancels, you grab the old value from the data attribute and put that back in.

HTML:

<form id="theform">
    <div>
        <div class="first editable">First Name</div>
        <div class="last editable">Last Name</div>


        <div class="edit">edit</div>
        <div class="save" style="display:none;">save</div>
        <div class="cancel" style="display:none;">cancel</div>
    </div>
</form>​

Javascript:

$('.edit').click(function() {
    $('.edit').hide();
    $('.save,.cancel').show();

    $('.editable').each(function(index, el) {
        $(el).attr('data-orig', $(el).html());           
        $(el).html('<input type="text" value="' + $(el).attr('data-orig') + '">');
    });
});    

$('.save').click(function() {
    $('.edit').show();
    $('.save,.cancel').hide();

      $('.editable').each(function(index, el) {
        $(el).attr('data-orig', '');   
        $(el).html($(el).find('input').val());
    });            
});

$('.cancel').click(function() {
    $('.edit').show();
    $('.save,.cancel').hide();

      $('.editable').each(function(index, el) {
        $(el).html($(el).attr('data-orig'));
        $(el).attr('data-orig', '');   
    });            
});​
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top