acr
acr

Reputation: 1746

keeping a div value after form submit

There are total 8 textboxes in my html form.I am displaying 2 of the textboxes by default and 6 are set to display:none.All these textboxes are wrapped with divs (named fa1 to fa8). I have added a button which will display the hidden divs(named from fa3 to fa8) upon each click.

html code:

<input  type="hidden" id="countfa" name="countfa" value="3" readonly>
<button type="button" onClick="AddNewFa();" id="addfa" > + Add New FA </button>

I am using below javascript to listen the click and count and display hidden divs

function AddNewFa() 
    {
        var facount = parseInt($('#countfa').val(),9) ;
        if( facount < 9)
            {
                facount = facount+1;

                for(i=3;i<9;i++)
                {
                    if( i<facount )
                        $('#fa'+i).slideDown("fast");
                    else
                        $('#fa'+i).slideUp("fast"); 

                }
                $('#countfa').val(facount);  

            }
             } 

The problem that I am facing here is after form submit countfa value changing back to its default value 3. So if I have showing all hidden div before form submit after clicking the button countfa value will be 8, and after form submit it will be 3 again. Is there anyway I can keep countfa value as 8 ? even after form submit ?

Upvotes: 2

Views: 860

Answers (2)

Aayush Agrawal
Aayush Agrawal

Reputation: 1394

I am not sure if i understood you correctly, but i faced a similar problem in the past and i resolved it rather easily. You can simply retrieve the value of countfa and then set its value.

Since you are using php, you can simply use this code

Note: Im assuming your using POST, if you are using GET then simply replace $_POST with $_GET

When you get to the part of your code printing the countfa div, simply use this code (Im assuming your using html and will introduce the php inline. Else just remove the <?php ?> tags

<?php

    if(isset($_POST['countfa'])){
     echo "<input  type=\"hidden\" id=\"countfa\" name=\"countfa\" value=\"$_POST['countfa']\" readonly>";
    }else{
     echo "<input  type=\"hidden\" id=\"countfa\" name=\"countfa\" value=\"3\" readonly>";
    }
?>

Upvotes: 2

Sanjo
Sanjo

Reputation: 1250

You can store the value in the browser local storage and check after page load if a previous value is stored and restore it if that's the case.

Here is the minimal working example: http://jsfiddle.net/C5Fe7/

$(function () {
    if (localStorage['countfa']) {
        $('#countfa').val(localStorage['countfa']);
    }

    $('#addfa').click(AddNewFa);
    $('form').submit(function () {
       localStorage['countfa'] = $('#countfa').val();
    });
});

Upvotes: 0

Related Questions