最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - keep checkboxes checked after page refresh - Stack Overflow

programmeradmin3浏览0评论

I have a couple of checkboxes. when any of them are clickd/checked and the search button is clicked, will grab their values and pass to the url as querystring and refresh the page returning results matching the passed query values. like this: mysite/result.aspx?k="Hospital" OR "Office" OR "Emergency"

I am able to grab the values after 'k='. I have "Hospital" OR "Office" OR "Emergency" captured and stored in a variable. Now I need to reset the checked state of checkboxes based on these values after the page reloads and forgets the previous state of the controls. I couldn't move any further than this. Can someone help me?

  var checkedOnes=decodeURI(location.href.match(/\&k\=(.+)/)[1]);
        if (value.length == 2) {
            $('input[name="LocType"][value="' + value[1] + '"]').prop('checked', true);
        }  

This is how I am capturing the checkboxes values and passing to the URL:

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

    window.location= url+checkboxValues;

    <div class="LocTypeChkBoxesSearch">
    <div class="LocTypeChkBoxes">
        <input name="LocType" type="checkbox" value="Hospital"/>HOSPITALS&#160;&#160;
        <input name="LocType" type="checkbox"  value="Office"/>  PHYSICIAN OFFICES&#160;&#160;
        <input name="LocType" type="checkbox"  value="Emergency"/>EMERGENCY CENTERS&#160;&#160;
        <input name="LocType" type="checkbox"  value="Out-Patient"/>OUT-PATIENT CENTERS&#160;&#160;
        <input name="LocType" type="checkbox" value="Facility"/>FACILITIES
    </div>
    <div class="searchBtnHolder"><a class="searchButton" href="#" type="submit" ><span>GO</span></a></div>
</div>

I have a couple of checkboxes. when any of them are clickd/checked and the search button is clicked, will grab their values and pass to the url as querystring and refresh the page returning results matching the passed query values. like this: mysite./result.aspx?k="Hospital" OR "Office" OR "Emergency"

I am able to grab the values after 'k='. I have "Hospital" OR "Office" OR "Emergency" captured and stored in a variable. Now I need to reset the checked state of checkboxes based on these values after the page reloads and forgets the previous state of the controls. I couldn't move any further than this. Can someone help me?

  var checkedOnes=decodeURI(location.href.match(/\&k\=(.+)/)[1]);
        if (value.length == 2) {
            $('input[name="LocType"][value="' + value[1] + '"]').prop('checked', true);
        }  

This is how I am capturing the checkboxes values and passing to the URL:

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

    window.location= url+checkboxValues;

    <div class="LocTypeChkBoxesSearch">
    <div class="LocTypeChkBoxes">
        <input name="LocType" type="checkbox" value="Hospital"/>HOSPITALS&#160;&#160;
        <input name="LocType" type="checkbox"  value="Office"/>  PHYSICIAN OFFICES&#160;&#160;
        <input name="LocType" type="checkbox"  value="Emergency"/>EMERGENCY CENTERS&#160;&#160;
        <input name="LocType" type="checkbox"  value="Out-Patient"/>OUT-PATIENT CENTERS&#160;&#160;
        <input name="LocType" type="checkbox" value="Facility"/>FACILITIES
    </div>
    <div class="searchBtnHolder"><a class="searchButton" href="#" type="submit" ><span>GO</span></a></div>
</div>
Share Improve this question asked Feb 27, 2012 at 21:31 Anjana SharmaAnjana Sharma 4,7955 gold badges40 silver badges51 bronze badges 3
  • have you considered using localStorage instead ? – mkk Commented Feb 27, 2012 at 21:33
  • not all browsers support html5 yet??!! – Anjana Sharma Commented Feb 27, 2012 at 21:37
  • Check up on cookies, you are going to have to actually save them somewhere it would seem to me, and since you indicate server side is out, session is not an option it seems. – Mark Schultheiss Commented Feb 27, 2012 at 21:43
Add a ment  | 

3 Answers 3

Reset to default 1

I've faced same problem, and my solution is HTML5 Local Storage. Add an function for colect checkboxes values

function(){
var data = $('input[name=checkboxName]:checked').map(function(){
        return this.value;
    }).get();
    localStorage['data']=JSON.stringify(data);
}

And onload function to check checkboxes

function(){
    if(localStorage&&localStorage["data"]){
        var localStoredData=JSON.parse(localStorage["data"]);
        var checkboxes=document.getElementsByName('checkboxName');
        for(var i=0;i<checkboxes.length;i++){
            for(var j=0;j<localStoredData.length;j++){
                if(checkboxes[i].value==localStoredData[j]){
                    checkboxes[i].checked=true;
                }
            }
        }
        localStorage.removeItem('data');
    }
}

It's work fine to me.

You shouldn't need JavaScript for this. You can check the $_GET parameters in your back-end code, and serve the page with the proper form element attributes.

In PHP, for example:

<input name="LocType" type="checkbox" value="Facility" <?php if (isset($_GET['LocType'] && $_GET['LocType'] == 'Facility') { ?> checked="checked" <?php } ?> /> FACILITIES

Try this.

//Split the url parameter value and get all the values in an array
var checkedOnes = decodeURI(location.href.match(/\&k\=(.+)/)[1]).split(" OR ");

//Find all the checkbox with name="LocType" and cache them in local variable
var $checkBoxes = $('input[name=LocType]');

//Loop through the array and find the corresponding checkbox element using filter
$.each(checkedOnes, function(i, val){
    $checkBoxes.filter('value=[' + $.trim(val.replace(/\"/g, '')) +']').prop('checked', true);
});

I am splitting the value of k by OR which will give all the values in an array. Next, loop through the array and find the corresponding checkbox by matching its value attribute and set its checked property to true using prop method.

发布评论

评论列表(0)

  1. 暂无评论