Thursday, 20 August 2020

After refreshing a button, text is changing in jquery

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>


from After refreshing a button, text is changing in jquery

No comments:

Post a Comment