3

I have a series of checkboxes on an HTML page and I would like to check the checkboxes based on corresponding HTML query string params.

e.g.

...path/page.html?i=1&j=1&x=0

would cause a page with three checkboxes to check 1 and 2 on load.

Can someone show me how to do this or point me in the direction of a suitable tutorial?

Many Thanks,

EDIT: A clarification, i, j and x are just picked off the top of my head, but they are boolean variables (1 = true, 0 = false) and each corresponds to a checkbox so:

i = one checkbox, the value in the example is 1, so the checkbox should be checked.
j = as above
x = one checkbox, the value in the example is 0, so the checkbox should not be checked.
1
  • well for one thing, do "i", "j" and "k" represent IDs of checkbox inputs? Commented Jan 28, 2009 at 16:18

5 Answers 5

2

Partially from W3Schools. This file will crate a single checkbox and check it depending on the http://example.com/index.html?j=? URL

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>

<script type="text/javascript">
function getUrlVars()
{
  var vars = [], hash;
  var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');

  for(var i = 0; i < hashes.length; i++)
  {
    hash = hashes[i].split('=');
    vars.push(hash[0]);
    vars[hash[0]] = hash[1];
  }
  return vars;
}

function doStuff()
{
  var GETVars = getUrlVars();
  if (GETVars['j']==1)
  {
    document.getElementById("myCheck").checked=true;
  }
}
</script>

<body onload="doStuff();">
  <form>
    <input id='myCheck' type="checkbox" />
  </form>
</body>
</html>
Sign up to request clarification or add additional context in comments.

Comments

2
function decode(s) {
    return decodeURIComponent(s).replace(/\+/g, " ");
}

function getQueryParams() {
    var query = {};

    document.location.search.replace(
        /\??(?:([^=]+)=([^&]*)&?)/g,
        function () {
            query[decode(arguments[1])] = decode(arguments[2]);
        });

    return query;
}

window.onload = function () {
    var query = getQueryParams();

    // check the checkboxes, assuming their ids are query param names
    var inputs = document.getElementsByTagName("input");

    for (var i = 0; i < inputs.length; i++) {
        var el = inputs[i];
        if (el.getAttribute("type") == "checkbox"
            && el.id in query) {
            el.checked = query[el.id] == "1";
        }
    }
};

And if you're using jQuery, it's much more concise:

$(document).ready(function () {
    $("input[type=checkbox]").each(function () {
        this.checked = new RegExp("(\\?|&)" + this.id + "=1")
            .test(document.location.search);
    });
});

Replace this.id with this.name if you want to refer to the check boxes by their names instead of ids.

Comments

1

Try this, remember that this code doesn't deal with malformed query strings.

function GetQueryStringParams() 
{
  var queryString = window.location.search.substring(1);
  var params = queryString .split('&');
  for (var i=0; i < params.length; i++) 
  {
    var pos = params [i].indexOf('=');
    if (pos > 0) 
    {
      var key = params [i].substring(0,pos);
      var val = params [i].substring(pos+1);

      switch(val) 
      {     
        case "1":
          document.getElementById(key).checked=true;
          break;
        case "0":
          document.getElementById(key).checked=false;
          break;
       }
    }
  }
}

2 Comments

Consider: document.getElementById(key).checked = val == "1";
Although your suggestion may provide a more succinct solution, it reduces readability.
0

First, you need to extract your parameters from URL. Here's a good way to do it.

Then, set the check box using 'checked' property:

domelement.checked = true;

Comments

0

First, get the params from the query string:

var params = new Object;
var query = window.location.search.substring(1);
if (query) {
  var vars = query.split('&');
  for (var i=0; i < vars.length; i++) {
    var pair = vars[i].split('=');
    params[unescape(pair[0])] = unescape(pair[1]);
  }
}

Then set your checkboxes accordingly:

if (params["i"] == 1) {
  document.getElementById("checkbox_i").checked=true;
}
if (params["j"] == 1) {
  document.getElementById("checkbox_j").checked=true;
}
// and so on

1 Comment

unescape is deprecated. You should use decodeURIComponent instead.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.