简体   繁体   中英

State checkbox after page reload

I need to save checkbox status after page reload. My Query string:

Mathes=1&Mathes=2&Mathes=3&Rols=2&Users=1&.......

How can I get this data? I wrote some code:

$(document).ready(function () {
    var value = window.location.href.match(/[?&]Matches=([^&#]+)/);
    $('input[name=Mathes]').each(function (index) {
        if (value[1] === $(this).val()) {
            $(this).attr('checked', 'checked');
        }
    });
});

But I can get only first element. How can I get it all by all parameters?

Have you try to use $.url().param('Mathes'); to get your Mathes?

Alexey, try to understand the concept, if you want to create multiple checkbox with same name, than the name is an array like:

<input type="checkbox" name="category[]" class="category" value="1" />
<input type="checkbox" name="category[]" class="category" value="2" />
<input type="checkbox" name="category[]" class="category" value="3" />
<input type="checkbox" name="category[]" class="category" value="4" />
<input type="checkbox" name="category[]" class="category" value="5" />

and get its value like:

var category= [];
$('input[class="category"]').each(function(){
    if($(this).is(':checked'))
    {
        category.push($(this).val());
    }
});

You could try out something like this in your js code,

$(document).ready(function () {
    var value = $(location).attr('href').split("?").pop();
  console.log("url"+$(location).attr('href'))
    var strparams=value.split("&");
    for(var i in strparams){
        strparams[i]=strparams[i].substring(strparams[i].indexOf("=")+1,strparams[i].length);
    }

    console.log(""+strparams);
    $('input[name=mathes]').each(function (index) {
        for(var j=0;j<strparams.length;j++){
        if (strparams[j] === $(this).val()) {
            $(this).attr('checked',true);
        }
        }
    });
});
  • I have split the url first based on "&" and then based on = and got the values
  • Then i have added another for loop to check all the values in the url with the values in the checkboxes

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM