0

I am a beginner in javascript ,I would to disable a html button forever after a click but my problem is when i refresh the web page the button return enabled

My code

<script type="text/javascript">
function fn(){
var t=document.getElementById("butn").disabled = true;
}

</script>
<body>
<input type="submit" value="ok" class="btn btn-default" id="butn" 
onclick="fn()"/>
</body>

thank you

Maak
  • 4,720
  • 3
  • 28
  • 39
  • 3
    Disabling it "for all the time" (sic) requires you to maintain that state somewhere on a server. If you're OK with "for a while", you can store it in a cookie or local storage. – Robby Cornelissen Apr 13 '18 at 11:42
  • forever is possible using a database where you save the button state and then load it everytime the page loads, the closest you can get to it, is saving the state to localStorage, but when the user cleans the browser cache, it will come back to original state. Take a Look here: https://stackoverflow.com/questions/49700776/append-new-element-only-once-on-click-and-save-it-to-local-storage-html-javascri/49701013#49701013 – Calvin Nunes Apr 13 '18 at 11:44
  • @RobbyCornelissen yeah, I removed that part, it makes sense. I don't know why I said that haha – Calvin Nunes Apr 13 '18 at 11:47

2 Answers2

0

If you reload the page, everything is loaded and executed from scratch. There is no state stored. If you want to keep a state, you can call localStorage.setItem('mybuttonstate', false) on button click.

When loading the page you can retrieve the state by localStorage.getItem('mybuttonstate') Put that e.g. in <body onload='init()'> :

function init(){
  document.getElementById("butn").disabled = localStorage.getItem('mybuttonstate')
}

This is just a client-side solution and does not work if you load it in another browser or you clear the local storage of the browser. If it needs to be very reliably stored, you need some more complex solution like sending the state to the server and store/retrieve it there. Then the user/client has no possibility to manipulate the state.

martink
  • 152
  • 5
0

Try this:

$(document).ready(function() {
      var myCookie = getCookie("disabledCookie");

    if (myCookie == null) {
      var t=document.getElementById("butn").disabled = false;
    }
    else {
      var t=document.getElementById("butn").disabled = true;
    }
 });


function fn(){
var t=document.getElementById("butn").disabled = true;
docCookies.setItem('disabledCookie', 'Disabled');
}
Dinkar Veer
  • 69
  • 1
  • 13