Skip to content Skip to sidebar Skip to footer

Keep Checkboxes Checked After Page Refresh

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

Solution 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(){
        returnthis.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.

Solution 2:

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:

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

Solution 3:

Try this.

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

//Find all the checkbox with name="LocType" and cache them in local variablevar $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.

Post a Comment for "Keep Checkboxes Checked After Page Refresh"