使用Javascript更改复选框

时间:2009-01-28 16:15:47

标签: javascript

我在HTML页面上有一系列复选框,我想根据相应的HTML查询字符串参数检查复选框。

e.g。

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

会导致带有三个复选框的页面在加载时检查1和2。

有人可以告诉我如何做到这一点,或者指出我的方向是合适的教程吗?

非常感谢,

编辑:澄清,我,j和x刚刚从头顶挑选,但它们是布尔变量(1 =真,0 =假),每个对应一个复选框,所以:

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.

5 个答案:

答案 0 :(得分:2)

部分来自W3Schools。此文件会创建一个复选框并根据http://example.com/index.html?j= 网址

进行检查
<!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>

答案 1 :(得分: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";
        }
    }
};

如果你正在使用jQuery,它会更简洁:

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

如果您想通过名称而不是ID来引用复选框,请将this.id替换为this.name

答案 2 :(得分:1)

试试这个,请记住此代码不会处理格式错误的查询字符串。

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

答案 3 :(得分:0)

首先,您需要从URL中提取参数。这是a good way to do it

然后,使用“checked”属性设置复选框:

domelement.checked = true;

答案 4 :(得分:0)

首先,从查询字符串中获取参数:

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

然后相应地设置复选框:

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