复选框(javascript)选择,第一项显示未定义?

时间:2015-06-09 11:04:59

标签: javascript html

我正在尝试选择并返回一些项目(复选框)。一切都很好,但第一项始终显示未完成。无法解决这个问题!

我的代码如下

function checkList () {
  var checked;
  var i;

  for( i = 0; i < document.form1.length; i++) {
    var element = document.form1[i]
    if (element.type == "checkbox"){
      if (element.checked == true){
        checked = checked + element.value + "<br/>";

      }

    }

  }
  document.getElementById('checked').innerHTML = checked;
}
<form name="form1">
  <input type="checkbox" name="checkbox1" id="checkbox1" value="Pen" />
  <label value="Earned" for="checkbox1">Pen</label>
  <br	/>
  <input type="checkbox" name="checkbox2" id="checkbox2" value="Book" />
  <label value="Earned" for="checkbox2" >Book</label>
  <br/>
  <input type="checkbox" name="checkbox1" id="checkbox3" value="Sharpner" />
  <label value="Earned" for="checkbox3">Sharpner</label>
  <br/>
  <input type="checkbox" id="checkbox4" name="checkbox1" value="Pencil" />
  <label value="Earned" for="checkbox4">Pencil</label>
  <br/> <br/>
  <input type="button" id="done" value="Done" onclick="checkList()" />
  <br/><br/>
</form>

<p >You are taking:</p>
<span id="checked"></span>

4 个答案:

答案 0 :(得分:2)

尝试更改

$('#my-today-button').click(function() {
    $('#calendar').fullCalendar('today');
});

到此......

<form name="form1">
  <input type="checkbox" name="checkbox1" id="checkbox1" value="Pen" />
  <label value="Earned" for="checkbox1">Pen</label>
  <br   />
  <input type="checkbox" name="checkbox2" id="checkbox2" value="Book" />
  <label value="Earned" for="checkbox2" for="checkbox">Book</label>
  <br/>
  <input type="checkbox" name="checkbox1" id="checkbox3" value="Sharpner" />
  <label value="Earned" for="checkbox3" for="checkbox" for="checkbox">Sharpner</label>
  <br/>
  <input type="checkbox" id="checkbox4" name="checkbox1" value="Pencil" />
  <label value="Earned" for="checkbox4">Pencil</label>
  <br/> <br/>
  <input type="button" id="done" value="Done" onclick="checkList()" />
  <br/><br/>
</form>

<p >You are taking:</p>
<span id="checked"></span>

代码中有多个重复项,例如(for =“”)

让我知道,谢谢

答案 1 :(得分:1)

更改

 var checked;  // like this, checked is undefined

 var checked = ""; // now it's simply empty

这是一个小提琴 http://jsfiddle.net/sq9938b0/

答案 2 :(得分:0)

问题是您将nm /usr/lib64/gcc/x86_64-suse-linux/4.8/libquadmath.a | grep -c fabsq 变量初始化为undefined。将字符串附加到undefined时,它将转换为字符串“undefined”,因此它出现在开头。

只需将其初始化为空字符串:checked

var checked = "";
function checkList () {
  var checked = "";
  var i;

  for( i = 0; i < document.form1.length; i++) {
    var element = document.form1[i]
    if (element.type == "checkbox"){
      if (element.checked == true){
        checked = checked + element.value + "<br/>";

      }

    }

  }
  document.getElementById('checked').innerHTML = checked;
}

答案 3 :(得分:0)

看一下以下步骤

checked = checked + element.value +“
”;

在第一个循环中,您尚未定义已选中。所以第一次是

checked = undefined + pen

初始化

var checked = ''