Reputation: 169
I have two divs with some 'deafult' content. When I click on link it changes html of that div. So I what to reset div html to initial content.
Example:
<a id="click1" href="#">Add</a><a id="click2" href="#">Reset</a>
<div id="click1_div">
<p>some text</p>
</div>
So when I click on Add jQuery will append some html, and when I click on Reset it should get back old html div content.
Any idea?
Upvotes: 3
Views: 27725
Reputation: 1183
Add this function somewhere on your page (preferably in the )
function clearBox(elementID)
{
document.getElementById(elementID).innerHTML = "";
}
Then add the button on click event
<button onclick="clearBox('cart_item')" />
In JQuery (for reference)
If you prefer JQuery you could do:
$("#cart_item").html("");
Upvotes: 1
Reputation: 1866
$(document).ready(function(){
var $container = $('#container'),
$content = $container.html(),
$newContent = '<br> Some content';
$('#add').on('click', function(){
$container.html($newContent);
});
$('#reset').on('click', function(){
$container.html($content)
});
});
http://codepen.io/mbrillaud/pen/doPRBL
Upvotes: 3
Reputation: 634
you cannot reset the content without storing the initial value. You can do somthing like this:
var initialContent;
$("#click1").click(function() {
initialContent = $("#click1_div").html();
// replace content here
}
And on reset you can write it back to the div:
$("#click2").click(function() {
$("#click1_div").html(initialContent);
}
Upvotes: 0
Reputation:
example: http://jsfiddle.net/WebJedi/4Lz43nco/1/
$(document).ready(function() {
var isChanged = false,
$clickDiv = $('#click1_div'),
defaultText;
$('#click1').on('click', function(e) {
e.preventDefault();
if(!isChanged) {
defaultText = $clickDiv.html();
isChanged = true;
$clickDiv.html('<strong>CHANGE TEXT</strong>');
} else {
alert('div is already changed');
}
});
$('#click2').on('click', function(e) {
e.preventDefault();
if(isChanged) {
$clickDiv.html(defaultText);
isChanged = false;
} else {
alert('no change detected');
}
});
});
Upvotes: 4
Reputation: 3830
Try this, .html()
will fetch you old html content save it to a variable and same .html()
method will replace the old content with new content:
$(document).ready(function(){
var old="";
$("#click1").click(function(){
old=$("#click1_div").html();
$("#click1_div").html("asdfad");
});
$("#click2").click(function(){
$("#click1_div").html(old);
});
});
Upvotes: 1
Reputation: 14862
I would add the original html to a variable to be used when the reset button is clicked. Something like:
//save original html of div
var originalHtml = $('#click1_div').html();
//when click on reset button, restore html
$('#click2').on('click', function(e){
e.preventDefault();
$('#click1_div').html(originalHtml);
});
Upvotes: 1
Reputation: 99
Perhaps you should save the old html before setting the new one.
var old_html = $("#click1_div").html();
And then use the old_html value to reset the innerhtml:
$("#click1_div").html(old_html);
Upvotes: 5