alexx0186
alexx0186

Reputation: 1557

How can I tell jquery to html( ) an element to its original value, before it was dynamically changed?

I have a div, and I used html() to change its content. I am doing a "cancel" button, and I would like to html() back to the original value.

Is there an efficient way to do this? I'm trying to avoid to html() the whole code again, as it doesn't look very good and is probably not the best practice.

Thanks a lot in advance. Regards

Upvotes: 2

Views: 1479

Answers (7)

Blazemonger
Blazemonger

Reputation: 92913

If at all possible, don't use .html to toggle content this way -- use two adjacent, nearly-identical elements, one with the old HTML and one with the new, and create a hidden CSS class with display: none and assign it to the second element. Then toggle this hidden class on both elements at the same time.

HTML:

<button class="cancel" id="cancel-original">Cancel</button>
<button class="cancel hidden" id="cancel-second">Cancelling...</button>

CSS:

.hidden {
    display: none;
}

JQuery:

$('button.cancel').click(function() {
    $('button.cancel').toggleClass('hidden'); // toggles both at once
});

http://jsfiddle.net/e9eLP/

Upvotes: 2

j08691
j08691

Reputation: 207900

By using jQuery's data() function you can easily hold the original value internally, and then restore it with something like this:

$('#a').click(function(){
    $('div').data('store',$('div').html()).html('foo');
});​​
$('#b').click(function(){
    $('div').html($('div').data('store'));
});
​

jsFiddle example. (Note that this example is just to illustrate how to store a value using data() and not meant for production code.)

Upvotes: 1

Developer
Developer

Reputation: 2006

You would need to save it in a variable before changing it:

<script>
var origHTML = $("#divid").html();
function ResetDiv(){
  $("#divid").html(origHTML);
}
</script>

Upvotes: 1

Tejs
Tejs

Reputation: 41246

You can save the previous HTML content into a variable and then restore from that variable on cancel.

var previousHtml = $('#someElement').html();

Then

$('#someElement').html(previousHtml);

Upvotes: 1

SLaks
SLaks

Reputation: 887469

The browser does not track the original value.
However, you can store the original HTML yourself into a variable when the page loads.

Upvotes: 1

DanRedux
DanRedux

Reputation: 9349

You can clone it when it's made, using jQuery, and when you cancel, delete that and clone the old version back in.

Upvotes: 1

Elliot Bonneville
Elliot Bonneville

Reputation: 53311

// store the old content
var myOldContent = $("#cancelbutton").html();

// change content
$("#cancelbutton").html(someNewContent);

// and change it back
$("#cancelbutton").html(myOldContent);

Upvotes: 5

Related Questions