如何在javascript中显示所选的复选框值

时间:2013-05-07 17:40:05

标签: javascript

如果单击打印按钮

,我想显示所选的复选框值

这是我的代码

<! 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>

如果我选择自行车复选框并单击打印按钮,它应显示唯一的自行车。

3 个答案:

答案 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);
}

Demo

此处,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>