如果单击打印按钮
,我想显示所选的复选框值这是我的代码
<! DOCTYPE html>
<head>
<script type="text/javascript">
function checkbox()
{
var bk=document.getElementById("bk").value;;
var cer=document.getElementById("cr").value;
document.writeln(" " + bk );
document.write(" " + cer);
}
</script>
</head>
<body>
<form>
<input type="checkbox" id="bk" name="vehicle" value="Bike">I have a bike<br></br>
<input type="checkbox" id="cr" name="vehicle" value="Car">I have a car<br></br>
<input type="submit" value=" Print " size="30" onClick="checkbox()">
</form>
</body>
</html>
如果我选择自行车复选框并单击打印按钮,它应显示唯一的自行车。
答案 0 :(得分:3)
我已经编辑了您的代码并根据您的需要进行了修改。请仔细阅读代码。
<! DOCTYPE html>
<head>
<script type="text/javascript">
function checkbox()
{
var bk=document.getElementById("bk").checked;;
var cer=document.getElementById("cr").checked;
if(bk) document.writeln(" Bike");
if(cer) document.write(" Car");
return false;
}
</script>
</head>
<body>
<form>
<input type="checkbox" id="bk" name="vehicle" value="Bike">I have a bike<br></br>
<input type="checkbox" id="cr" name="vehicle" value="Car">I have a car<br></br>
<input type="submit" value=" Print " size="30" onClick="return checkbox();">
</form>
</body>
</html>
答案 1 :(得分:0)
此函数将创建一个数组,其中包含表单中每个选中项的值:
function checkbox()
{
var checked = [].reduce.call(document.forms[0].vehicle, function(current, item) {
if (item.checked) {
current.push(item.value);
}
return current;
}, []);
alert(checked);
}
此处,document.forms[0].vehicle
会在表单中返回名称为vehicle
的复选框;我正在使用document.forms[0]
,因为您没有给表单命名:)
答案 2 :(得分:0)
继承人你的代码..这应该解决你的问题..
<! DOCTYPE html>
<head>
<script type="text/javascript">
function checkbox()
{
var bk=document.getElementById("bk").checked;;
var cer=document.getElementById("cr").checked;
if(bk) document.writeln(" Bike");
if(cer) document.write(" Car");
return false;
}
</script>
</head>
<body>
<form>
<input type="checkbox" id="bk" name="vehicle" value="Bike">I have a bike<br></br>
<input type="checkbox" id="cr" name="vehicle" value="Car">I have a car<br></br>
<input type="submit" value=" Print " size="30" onClick="return checkbox();">
</form>
</body>
</html>