After refreshing a button, text is changing in jquery

Viewed 1001

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>

5 Answers

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>

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>

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)

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.

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.

Related