我需要通过<a href></a>
发送复选框值(在1到N个复选框的数字中)。
我正在考虑使用javascript,但我不知道是否可以在<form></form>
外部的上下文中使用复选框值。
有什么建议吗?
EDIT-1:我想获取复选框值,然后导航到包含这些值作为GET参数的网址,即index.php?c1=1&c2=0&c3=0
答案 0 :(得分:2)
我认为您要通过更改href
属性of an
a`标记来提交复选框值,这样当用户点击它时,它们就会被发送到提交了复选框值的网址作为GET参数。
最简单的方法是使用jQuery;我建议你导入它,因为它会节省你很多时间。如果你想要一个可靠的纯Javascript解决方案,请告诉我,我将告诉你如何在没有jQuery的情况下做到这一点。
你有复选框,(例如我们会说)1到5:
<input type="checkbox" id="cb1" value="1"/>
<input type="checkbox" id="cb2" value="0"/>
<input type="checkbox" id="cb3" value="0"/>
<input type="checkbox" id="cb4" value="0"/>
<input type="checkbox" id="cb5" value="1"/>
通过给他们一个类似的id,我们可以很容易地得到复选框的值:
function someFunction()
{
var id=1;
var getVars = "";
while($("#cb"+id).length > 0)
{
getVars += "cb" + id + "=" + $("#cb"+id).val() + "&";
}
var href = "index.php?" + getVars; //Change "index.php" to the name of the page you want to navigate to.
$("a").attr("href", href);
}
这会将href
标记的<a>
属性设置为正确的新网址:
<a href="index.php?cb1=1&cb2=0&cb3=0&cb4=0&cb5=1">
除非您希望此函数更改页面上所有href
标记的<a>
属性,否则您应该为a标记指定id或类以在jQuery函数中标识它。
看到上面的编辑,因为您不需要更改标签的属性,您只需删除:
$("a").attr("href", href);
并将其替换为
parent.location = href;
这将在函数执行时立即将用户发送到带有GET变量的页面。
答案 1 :(得分:1)
不要这么做。只需按常规方式将它们放入GET表单中,然后单击链接提交表单。
<form name="myform" action="index.php">
<input type="checkbox" name="c1" value="1" />
<input type="checkbox" name="c2" value="1" />
<input type="checkbox" name="c3" value="1" />
<input type="checkbox" name="c4" value="1" />
<input type="checkbox" name="c5" value="1" />
<a href="#" onclick="myform.submit(); return false;">send</a>
</form>
或者,为了完全不使用JS(因此它也适用于屏幕阅读器,古代手机等),使用常规的提交按钮,但引入一些CSS使其看起来像一个链接:
<form action="index.php">
<input type="checkbox" name="c1" value="1" />
<input type="checkbox" name="c2" value="1" />
<input type="checkbox" name="c3" value="1" />
<input type="checkbox" name="c4" value="1" />
<input type="checkbox" name="c5" value="1" />
<input type="submit" value="send" class="link" />
</form>
与例如
input[type=submit].link {
background: none;
border: none;
color: blue;
text-decoration: underline;
cursor: pointer;
}