5

When I click a button the text will change every time. For example when I go to the page it shows 'Close'. If I click that button and it's value will change to 'Open'. It happens in another way also. If I click the 'Open' then it changes to close.

However the problem is if the button is in 'Open' state and if I do refresh it's changing to 'Close'. But if it's in 'Close' and I click refresh it's not changing to 'Open'.

What I need is after every click it should change from open to close or close to open. But after refresh also it should be in the same state. it should not get changed. How should I do it.

function changeStatus() {
  console.log("Hi");
  
  var val = document.getElementById("openClose").value;
  $.ajax({
    type: 'POST',
    url: '/change/me',
    data: {
      'val': val
    },
    success: function(result) {
      alert("The text has been changed");

    }
  })
}

$(".changeme").click(function() {
  $(this).text(function(i, text) {
    return text === 'Close' ? 'Open' : 'Close'
  })
})
<!--Stylesheets-->
<link href="https://netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css" rel="stylesheet">
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet">
<link href="http://getbootstrap.com/2.3.2/assets/css/bootstrap.css" rel="stylesheet" />


<!--JS files-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>

<button class="btn btn-danger changeme" onclick="changeStatus()" id="openClose">Close</button>
</div>
  • 4
    u might want to think of to use `localstorage` or `sessionstorage` to keep the temporary value so that you can work it out when the page refresh – Se0ng11 Aug 18 '20 at 08:12
  • 2
    Does this answer your question? [How to get JS variable to retain value after page refresh?](https://stackoverflow.com/questions/16206322/how-to-get-js-variable-to-retain-value-after-page-refresh) – Karan Aug 18 '20 at 08:14
  • I am not sure how to use localstorage or session storage. what is setitem or getitem in session or local storage?how do iuse it in my script? –  Aug 18 '20 at 08:51
  • I tried this now $(".changeme").click(function (){ $(this).text(function (i, text) { return text === 'Close' ? 'Open' : 'Close' }) localStorage.setItem("openClose", text); }) but it's not working –  Aug 18 '20 at 09:11

5 Answers5

4

Version with local storage (but you can't test it inside snippet, snippet don't give acces to local storage, but codepen does) Demo on codepen

let store = window.localStorage
function changeStatus() {
  let val 
  store.getItem('btnstat') === "Open"? checkUpdLocal("Close") : checkUpdLocal("Open") // toggle status
  
  val = store.getItem('btnstat')
  $.ajax({
    type: 'POST',
    url: '/change/me',
    data: {
      'val': val
    },
    success: function(result) {
      alert("The text has been changed");

    }
  })
}

function checkUpdLocal(stat){
  if(!store.getItem('btnstat')){ // if local storage does not exist
    store.setItem('btnstat', "Close") // close by default
  }else if(store.getItem('btnstat') && !stat){ // if storage exist but we don't change status (first ini) - change buttno text
    $('.changeme').html(store.getItem('btnstat'))
  }
  if(stat){ // setter
    store.setItem('btnstat', stat)
    $('.changeme').html(stat)
  }else{
    return store.getItem('btnstat') // getter
  }
}
$( document ).ready( function(){checkUpdLocal()})
<!--Stylesheets-->
<link href="https://netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css" rel="stylesheet">
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet">
<link href="http://getbootstrap.com/2.3.2/assets/css/bootstrap.css" rel="stylesheet" />


<!--JS files-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>

<button class="btn btn-danger changeme" onclick="changeStatus()" id="openClose">Close</button>
</div>
Greg--
  • 636
  • 4
  • 16
1

Here is an example of using sessionStorage to persist state temporarily.

The sessionStorage object stores data for only one session (the data is deleted when the browser tab is closed). sessionStorage will not work on old browsers that do not have support for it.

    <script type="text/javascript">
            $(document).ready(function () {
                if (sessionStorage.getItem("changeState") == null) {
                    $(".changeme").text("Close");
                    sessionStorage.setItem("changeState", "Close");
                } else {
                    if (sessionStorage.getItem("changeState") === "Close") {
                        $(".changeme").text("Close");
                    } else {
                        $(".changeme").text("Open");
                    }
                }
    
                $(".changeme").click(function () {
                    if (sessionStorage.getItem("changeState") === "Close") {
                        $(this).text("Open");
                        sessionStorage.setItem("changeState", "Open");
                    } else {
                        $(this).text("Close");
                        sessionStorage.setItem("changeState", "Close");
                    }
                })
            });
   </script>
Sandeep
  • 1,182
  • 3
  • 11
  • 26
1

When you use localStorage, you have to check if the value has been saved before

$( document ).ready(function(){
  if(localStorage.getItem("openClose")!==undefined){
    $('.changme').text(localStorage.getItem("openClose"));

});

(edited to put the lookup in ready function)

Bryn Lewis
  • 580
  • 1
  • 5
  • 14
0

It's the older way, but you could also save the state in a cookie.

Save it with:

   document.cookie = "Open";

on page load, retrieve it with `

   var state = document.cookie;

This is very awkward though; I would recommend using a cookie library to manipulate these.

Nathaniel Tagg
  • 385
  • 2
  • 14
0

Just one more answer if someone is thinking what if cookies are disabled in the browser and you still want to save the state of the elements on your web page according to the user's interaction.

In this case, you can save the state of the elements by doing AJAX call and save states to the database when the user changes the state of elements. But this would be a good approach only if you have lots of elements state to be saved. For 1-2 elements don't try this method. It will be inefficient.

By using cookies approach:

of course, you can store the 'state' in a cookie, and then retrieve that cookie when the page gets refreshed.

As cookies only admit strings, you can convert javascript objects to strings using

var str = JSON.stringify(obj);

and to convert back use

var obj = JSON.parse(str);

(JSON functions are supported in modern browsers).

This way you can save/retrieve a javascript object, you could store (in your case) some coordinates, positions, sizes, whatever you need.

Manish
  • 909
  • 6
  • 15