Сохранение отмеченных флажков после обновления страницы - PullRequest
1 голос
/ 25 февраля 2012

Пользователи устанавливают флажки и нажимают «Выбрать», результаты отображаются, но затем флажки теряют свое проверенное состояние, и это приводит пользователей в замешательство относительно того, что они проверяли. Я пытаюсь сохранить состояние флажков после обновления страницы. Я пока не могу этого достичь, но надеюсь, что это выполнимо. Может ли кто-нибудь помочь мне в правильном направлении?

Emergency Centers<input name="LocType" type="checkbox"  value="Emergency"/>&#160; 
Out-Patient Centers<input name="LocType" type="checkbox"  value="Out-Patient"/>&#160; 
Facilities<input name="LocType" type="checkbox" value="Facility"/>
<div class="searchBtnHolder"><a class="searchButton" href="#" type="submit"><span>Search</span></a></div>



$(document).ready(function() {  
    var url = "http://mysite/sites/dev/contact-us/Pages/LocationSearchTestPage.aspx?s=bcs_locations"; 
    $('a.searchButton').click(function(){ 

    var checkboxValues = $("input[name=LocType]:checked").map(function() {
    return "\"" + $(this).val() + "\"";}).get().join(" OR ");

       //Now use url variable which has all the checked  LocType checkboxes values and jump to url 

       window.location = url+'&k='+checkboxValues;

    });

    //Keep the selected checked on page redirect
    var value = window.location.href.match(/[?&]k=([^&#]+)/) || [];
    if (value.length == 2) {
        $('input[name="LocType"][value="' + value[1] + '"]').prop('checked', true);
    }  


});

Ответы [ 2 ]

2 голосов
/ 22 января 2013

не уверен, если вы все еще заинтересованы в этом, но у меня была такая же проблема некоторое время назад, и я нашел этот общий фрагмент JS, который сохраняет флажок состояния:

// 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;';
}

Просто убедитесь, что вашК флажкам прикреплено onChange= persistCheckBox(this);, например.

<label for= "LocType">User Preference</label>
<input name= "LocType" type= "checkbox" onChange= persistCheckBox(this);"/>

А также onLoad в вашем открывающем теге body:

<body onload="restorePersistedCheckBoxes();">

0 голосов
/ 25 февраля 2012

Я был бы более склонен использовать веб-хранилище HTML5 (быстрее и безопаснее), но cookie-файлы также справились бы с этой задачей.Вот ссылка на некоторые примеры с использованием HTML5 http://www.w3schools.com/html5/html5_webstorage.asp

...