Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing checkboxes using Javascript

Tags:

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.
like image 211
Konrad Avatar asked Nov 25 '25 06:11

Konrad


1 Answers

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>
like image 62
Grant Avatar answered Nov 26 '25 21:11

Grant



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!