Home > Software engineering >  Show checkbox value in URL
Show checkbox value in URL

Time:11-15

I have a page that makes a query with Ajax. Checkboxes on this page work without any URL. What I want to do is to be able to load this data with URL. So when I enter a value in the url, I want that data to come automatically.

$checkboxes = $('input[type=checkbox');
$checkboxes.change(function(){
    window.location.hash = 'marka='   $checkboxes.filter(':checked').map(function(){
        return this.value;   
    }).get().join(",");
    console.log(window.location.hash);
});
 
 <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
 <div >
 <input  type="checkbox" id="marka_1" value="1">
 <label  for="marka_1">Value 1 </label>
 <input  type="checkbox" id="marka_2" value="2">
 <label  for="marka_21">Value 2 </label>
 <input  type="checkbox" id="marka_3" value="3">
 <label  for="marka_3">Value 3 </label>
 <input  type="checkbox" id="marka_4" value="4">
 <label  for="marka_4">Value 4 </label>
  </div>

I want to load data via URL

CodePudding user response:

If I understand correctly, you want to both save checkbox state to the hash, and then load it again when someone visits a URL with checkbox info in the hash.

You already have the code which saves the checkbox state to the hash. You're using a simple comma-separted list like #marka=2,4. Loading that data back is simple enough:

  • read the hash with window.location.hash;
  • remove the #;
  • remove marka= so you are left only with the values of the checked checkboxes;
  • create an array of the values left;
  • iterate over all checkboxes and check those whose values are in that array;

Something like this:

function loadCheckboxState() {
    // Get the hash, and remove the '#', we are left with marka=2,4
    let string = window.location.hash.substring(1);

    // Remove 'marka=', so we are left with 2,4
    string.replace('marka=', '');

    // Create an array of the ids left, [2,4]
    let checked = string.split(',');

    // Now check the checkboxes whose value is in the array
    $checkboxes.prop('checked', function () {
        return checked.indexOf(this.value) >= 0;
    });
}

You could run it on page load, eg:

$(document).ready(function() {
    loadCheckboxState();
});

Note there are a few minor issues in your code:

  • jQuery 1.9.1 is ancient (2013!), you should be using a more recent version;

  • Typo: $('input[type=checkbox');

  • Typo: for="marka_21";

  • Use var (or let) to declare your variables;

  • Related