使用javascript/jQuery根据网址值自动选中复选框 [英] auto checkbox based from url value using javascript/jQuery
问题描述
是否可以使用javascript/jQuery来实现?
Is there way to or it is possible to do it using javascript/jQuery?
基于链接的URL:第一个将检查A型和B型,第二个示例将检查D型
Based Link URL: first one will check Type A and Type B and second example will check Type 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" />
有什么建议和建议吗?
推荐答案
这样做:
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
".然后:
Consider the url is 'http://sample.com?type=A&type=C
'. Then:
-
i
是该URL中"?
"符号的索引 -
.substr() 将从网址中剪切
type=A&type=C
部分.剪切后,我们将得到以下字符串:
i
is the index of '?
' sign in that url.substr() will cut
type=A&type=C
part from the url. After the cut, we will have this string:
"type=A&type=C"
.replace() 会删除上述字符串中的"type ="部分:
.replace() removes "type=" parts from the above mentioned string:
"A&C" //after replace
.split() 拆分将该字符串放入数组:
.split() splits that string into array:
["A","C"]
$.inArray() 检查当前["A","C"]
数组中.如果是,则checks
(.prop('checked',true)
)checkbox
.
$.inArray() checks whether value of current checkbox
is in the ["A","C"]
array. If it is, then checks
( .prop('checked',true)
) the checkbox
.
这篇关于使用javascript/jQuery根据网址值自动选中复选框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!