0

I am having a div with lot of elements inside the div. For some scenario i want to reset the value for the div's element to the initial status.

Is there any way to do this??

if($(window).width()<=960){
    $('#desktopCart').html(/i want to reset this element/);
    } 

    if($(window).width()>960){
    $('#mobileCart').html("/i want to reset this element/");
    }
Naju
  • 1,541
  • 7
  • 27
  • 59

4 Answers4

1

use .empty() of jquery

$("#divId").empty();

It will remove all the child elements and text in that particular element.

If you want to restore the initial state of the div, you should save the initial innerHtml to a variable a document.ready(). Like,

   var desktopCart;
   var mobileCart;
    $(document).ready(function(){
     desktopCart=$('#desktopCart').html();
     mobileCart=$('#mobileCart').html();

    });

Then restore the html whenever you want,

if($(window).width()<=960){
$('#desktopCart').html(desktopCart);
} 

if($(window).width()>960){
$('#mobileCart').html(mobileCart);
}
Anoop Joshi P
  • 25,373
  • 8
  • 32
  • 53
1

First clone the element instead of saving the content. Then use replaceWith to restore it.

  $(document).ready(function() {
      var divClone = $("#mobileCart").clone();
      if($(window).width()<=960){
    $('#desktopCart').html(/i want to reset this element/);
    } 

    if($(window).width()>960){
      $("#mobileCart").replaceWith(divClone);
    }
    });

For further reference, please see the below link.

How can I "reset" <div> to its original state after it has been modified by JavaScript?

Community
  • 1
  • 1
RGS
  • 5,131
  • 6
  • 37
  • 65
1

try:

$( document ).ready(function() {
var initialValue =$('#mobileCart').html();
});
if($(window).width()<=960){
$('#desktopCart').html(initialValue);
} 

if($(window).width()>960){
$('#mobileCart').html(initialValue);
}
Paweł
  • 409
  • 3
  • 13
1

What if I have multiple elements ? And want to save the elements' state at regular intervals ? And regularly reset them ? There might not be just one of them .... maybe I will have a and p and div and too many of them. But I want to reduce typing ? What do I do ?

I am glad you asked.

// Write Once: Use Anywhere functions

$.fn.reset = function () {    
    var list = $(this); // list of elements

    for(var i = 0, len = list.length; i < len; i++){ 
        list.eq(i).text(list.eq(i).data("initValue"));    
    }
};

$.fn.saveState = function () {
    var list = $(this); // list of elements

    for(var i = 0, len = list.length; i < len; i++){
        list.eq(i).data("initValue", list.eq(i).text());    
    }
}

$("div").saveState(); // simple call to save state instantly !

// value change!
$("div:nth-child(2)").text("99999");

$(window).resize(function () {
    if ($(window).width() <= 960) {
        $("div").reset(); // simple call to reset state instantly !
    }
});

DEMO Resize window

Gaurang Tandon
  • 6,504
  • 11
  • 47
  • 84