使用javascript / jQuery从url值开始的自动复选框

时间:2012-07-12 14:56:54

标签: javascript jquery checkboxlist

有没有办法或者可以使用javascript / jQuery来实现?

基于链接的URL:第一个将检查类型A和类型B,第二个示例将检查类型D

?type=A&type=C or ?type=D

我目前的表格:

<form name="input" action="" method="post" ><br />
Select Type: <br />
<input type="checkbox" name = "type" value="A" /> A <br />
<input type="checkbox" name = "type" value="B"  /> B <br />
<input type="checkbox" name = "type" value="C"  /> C <br />
<input type="checkbox" name = "type" value="D" /> D <br /> <br />
<input type="submit" value="Submit" />

有任何提示并建议这样做吗?

2 个答案:

答案 0 :(得分:9)

这样做:

var i = document.location.href.lastIndexOf('?');
var types = document.location.href.substr(i+1).replace(/type=/g,'').split('&');
$('input[name="type"]').prop('checked',function(){
     return $.inArray(this.value,types) !== -1;
});

解释

请注意网址为“http://sample.com?type=A&type=C”。然后:

  • i是该网址“?”的索引
  • .substr()会从网址中删除type=A&type=C部分。切割后,我们将有这个字符串:

    "type=A&type=C"
    
  • .replace()从上面提到的字符串中删除“type =”部分:

    "A&C"   //after replace
    
  • .split()将该字符串拆分为数组:

     ["A","C"]
    
  • $.inArray()检查当前checkbox的值是否在["A","C"]数组中。如果是,则checks.prop('checked',true)checkbox

答案 1 :(得分:0)

question显示了使用javascript检查查询字符串参数的解决方案。顶部还有一个链接到可能的duplicate question,它使用JQuery提供解决方案。

一旦确定了querty字符串参数,就可以使用jQuery来检查该框(详见another question):

$('input[value="A"]').prop("checked", true);