Konrad
Konrad

Reputation: 40947

Changing checkboxes using Javascript

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.

Upvotes: 3

Views: 1760

Answers (5)

Ateş Göral
Ateş Göral

Reputation: 140050

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.

Upvotes: 2

Grant
Grant

Reputation: 12039

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>

Upvotes: 2

Phaedrus
Phaedrus

Reputation: 8421

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;
       }
    }
  }
}

Upvotes: 1

nezroy
nezroy

Reputation: 3186

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

Upvotes: 0

buti-oxa
buti-oxa

Reputation: 11431

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;

Upvotes: 0

Related Questions