persistenza di valori checkbox

voti
2

Ho una pagina con diversi caselle di controllo. Posso controllare alcuni di loro e andare alla pagina successiva, quando tornerò in questa pagina, queste caselle devono rimanere controllato come erano prima visualizzando un'altra pagina. Hai bisogno di farlo con Javascript. Qualsiasi indizio ??

È pubblicato 20/07/2009 alle 16:28
fonte dall'utente
In altre lingue...                            


3 risposte

voti
1

Avrete bisogno di persistere loro fra le pagine-richieste. È possibile utilizzare le sessioni o cookie per fare questo. Che tipo di server stanno lavorando, e con quale tipo di linguaggio server-side?

domande precedenti sul modo da avere la scrittura indirizzo / leggere cookie da JavaScript.

Risposto il 20/07/2009 a 16:30
fonte dall'utente

voti
4

Se si è limitato a JavaScript solo e nessun linguaggio lato server Penso che si sono lasciati di leggere / scrivere i cookie per mantenere lo stato. Come altri hanno fatto riferimento, tecnologie server side sono molto meglio a questo, ma se è necessario:

JavaScript codice di esempio biscotto (riferimento: http://www.quirksmode.org/js/cookies.html ):

function createCookie(name,value,days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        var expires = "; expires="+date.toGMTString();
    }
    else var expires = "";
    document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}

function eraseCookie(name) {
    createCookie(name,"",-1);
}
Risposto il 20/07/2009 a 16:37
fonte dall'utente

voti
0

Non credo che ci sia alcun modo ragionevolmente complicato farlo senza avere alcun accesso al codice lato server, perché al minimo che è necessario installare il codice e anche identificare i controlli HTML, ad esempio, al fine di controllarli. I 'm dare il codice ragionevole che fa quello che si vuole qui di seguito.

Note importanti:

  1. Il codice richiede che ciascuna casella è assegnato un attributo id distinta.
  2. Lo stato di controllo è memorizzato in un cookie denominato 'JS_PERSISTENCE_COOKIE'. Sarebbe meglio per memorizzare il nome di questo cookie in una variabile, invece di inserirli nel codice in un paio di luoghi separati come ho fatto io. Che tipo di variabile dovrebbe memorizzare il nome dipende dal vostro app e requisiti.
  3. Sarebbe meglio per confezionare il codice all'interno di un oggetto anziché come un gruppo di funzioni libere come ho fatto. Tuttavia, questo non è rilevante per la tua domanda iniziale.
  4. Dopo aver cliccato su alcune caselle di controllo, è possibile simulare "navigare per tornare a questa pagina" premendo CTRL + F5. solo F5 non è sufficiente.

Ecco il codice e alcuni HTML di esempio per il test:

<body onload="restorePersistedCheckBoxes()">
    <input type="checkbox" id="check1" onclick="persistCheckBox(this)" />
    <input type="checkbox" id="check2" onclick="persistCheckBox(this)" />
    <input type="checkbox" id="check3" onclick="persistCheckBox(this)" />
    <input type="button" value="Check cookie" 
           onclick="alert(document.cookie)" />
    <input type="button" value="Clear cookie"
           onclick="clearPersistenceCookie()" />

    <script type="text/javascript">
        // This function reads the cookie and checks/unchecks all elements
        // that have been stored inside. It will NOT mess with checkboxes 
        // whose state has not yet been recorded at all.
        function restorePersistedCheckBoxes() {
            var aStatus = getPersistedCheckStatus();
            for(var i = 0; i < aStatus.length; i++) {
                var aPair = aStatus[i].split(':');
                var el = document.getElementById(aPair[0]);
                if(el) {
                    el.checked = aPair[1] == '1';
                }
            }
        }

        // This function takes as input an input type="checkbox" element and
        // stores its check state in the persistence cookie. It is smart
        // enough to add or replace the state as appropriate, and not affect
        // the stored state of other checkboxes.    
        function persistCheckBox(el) {
            var found = false;
            var currentStateFragment = el.id + ':' + (el.checked ? '1' : '0');
            var aStatus = getPersistedCheckStatus();
            for(var i = 0; i < aStatus.length; i++) {
                var aPair = aStatus[i].split(':');
                if(aPair[0] == el.id) {
                    // State for this checkbox was already present; replace it
                    aStatus[i] = currentStateFragment;
                    found = true;
                    break;
                }
            }
            if(!found) {
                // State for this checkbox wasn't present; add it
                aStatus.push(currentStateFragment);
            }
            // Now that the array has our info stored, persist it
            setPersistedCheckStatus(aStatus);
        }

        // This function simply returns the checkbox persistence status as
        // an array of strings. "Hides" the fact that the data is stored
        // in a cookie.
        function getPersistedCheckStatus() {
            var stored = getPersistenceCookie();
            return stored.split(',');
        }

        // This function stores an array of strings that represents the 
        // checkbox persistence status. "Hides" the fact that the data is stored
        // in a cookie.
        function setPersistedCheckStatus(aStatus) {
            setPersistenceCookie(aStatus.join(','));
        }

        // Retrieve the value of the persistence cookie.
        function getPersistenceCookie()
        {
          // cookies are separated by semicolons
          var aCookie = document.cookie.split('; ');
          for (var i=0; i < aCookie.length; i++)
          {
            // a name/value pair (a crumb) is separated by an equal sign
            var aCrumb = aCookie[i].split('=');
            if ('JS_PERSISTENCE_COOKIE' == aCrumb[0]) 
              return unescape(aCrumb[1]);
          }
          return ''; // cookie does not exist
        }

        // Sets the value of the persistence cookie.
        // Does not affect other cookies that may be present.
        function setPersistenceCookie(sValue) {
            document.cookie = 'JS_PERSISTENCE_COOKIE=' + escape(sValue);
        }

        // Removes the persistence cookie.
        function clearPersistenceCookie() {
            document.cookie = 'JS_PERSISTENCE_COOKIE=' +
                              ';expires=Fri, 31 Dec 1999 23:59:59 GMT;';
        }
    </script>

</body>
Risposto il 20/07/2009 a 17:26
fonte dall'utente

Cookies help us deliver our services. By using our services, you agree to our use of cookies. Learn more