Page 1 of 1

Save button enabled state

Posted: Tue Feb 12, 2013 9:14 pm
by SerbanSpire
I have discovered a peculiar thing with my old enable/disable button issue. Code example:

Code: Select all

<?php 
 print"<form name='buttons_form'>";
 print"<input type='button' name='button1' value='ActiveButton' onclick='enable_button2()><br>";
 print"<input type='button' name='button2' disabled value='DisabledButton' onclick='enable_button3()'><br>";
 print"<input type='button' name='button3'  disabled value='DisabledButton'>";
 print"</form>";
?>

<script language="javascript">

 function enable_button2(){
  if (document.buttons_form.button1.disabled==false){
   document.buttons_form.button2.disabled=false

  }else{
   document.buttons_form.button2.disabled=true
  }
 }
 function enable_button3(){
  if (document.buttons_form.button2.disabled==false){
   document.buttons_form.button3.disabled=false

  }else{
   document.buttons_form.button3.disabled=true
  }
 }
How can i save the enabled state of the buttons (button2 and button3) after i refresh the page? Following the code, it will enable the button2 after button 1 is pressed and will enable button3 after button2 is pressed. If you refresh the page the buttons will become disabled again. I don't want that. How can i solve this? Thanks in advance.

Re: Save button enabled state

Posted: Wed Feb 13, 2013 3:00 am
by Jackolantern
Unfortunately, there is not a simple way to accomplish this with JavascripS alone. What you are referring to is "state", as in, the state of the JS application at any given time. Javascript, by default, loses all of its state when you reload a page in any way. As HTML5 and the related JS APIs become more widespread, Local Storage will be able to fix this, but we are still a ways out from being able to depend on this, especially considering that Local Storage is moving a bit slower in browser implementation than many other features.

For now, there are a number of ways to deal with this. Here is a description of one possible solution (and apparently is the way that FB handles it or used to). Another popular way is like the previous link, but instead you set up events to send the state to the database through AJAX when the user goes to another page or reloads (this is different from the previous link in that the previous was syncing the state to the database on an interval), and then simply reload the state when the page is accessed again. There are also software options that perform these solutions under the hood, such as this library called JS Page Cookie.

Maybe spend some time looking at various options on Google to find one you think will work for you :)

Re: Save button enabled state

Posted: Thu Feb 14, 2013 5:27 pm
by hallsofvallhalla
you could use a post then just

Code: Select all

var isstate = "<?php echo $_POST['buttonstate']; ?>";
if(isstate)
{
change state of button ....
}