wwli
wwli

Reputation: 2681

Keep javascript changes after page posts to server and returned error

I have a rails form with a few buttons. When user clicks certain button I remember the change in hidden form fields.

After the form was posted to server and reloaded (if certain errors happened in the form) the hidden fields are reset. I cannot keep what has been clicked. Here is the code trying to keep what has been clicked

  <div class="btn-group col-sm-12">
          <button type="button" class="btn btn-default col-sm-6 active" id="user">I am user</button>
          <button type="button" class="btn btn-default col-sm-6" id="admin"> I am an admin</button>
  </div>  


<input id="profile_user" name="profile[user]" type="hidden" value="false" />
<input id="profile_admin" name="profile[admin]" type="hidden" value="false" />   



      function show_user(){

            $("#user").addClass("active");
            $("#admin").removeClass("active");    
            $("#profile_user").val("true");
            $("#profile_admin").val("false");

        }

        function show_admin(){
            $("#admin").addClass("active");
            $("#user").removeClass("active");
            $("#profile_user").val("false");
            $("#profile_admin").val("true");        
        }


    $(function(){
        console.log("reload");  
        console.log($("#profile_user").val());
            if($("#profile_admin").val() == "true"){
                show_admin();       
            }else{
                show_user();
           }
          $('#user').click(function() {
            show_user();
         });

         $('#admin').click(function() {
           show_admin();
         });
     });

Or what is a better way to keep javascript change in rails form through server push and retuen?

Upvotes: 0

Views: 89

Answers (1)

Piotr Wu
Piotr Wu

Reputation: 1362

You can save it in localStorage, and check if it is fill on document start. Save your data in this way:

localStorage.setItem('myValue',myValue)

So first when page is loaded check if localStorage is not empty:

if (localStorage.length != 0){
   $('#yourField').val(localStorage.myValue);
}else{
    localStorage.setItem('myValue',myValue);
}

Upvotes: 1

Related Questions