添加新复选框会取消选中其他复选框

时间:2015-06-09 11:19:52

标签: javascript html checkbox

当我添加一个新复选框时,旧复选框被设置为未选中(即使已选中它们)。我该如何解决?

这里有我的代码:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<script type="text/javascript">
function zaza() {
    document.body.innerHTML+=
        '<input type="checkbox" name="vehicle" value="Bike"> I have a bike<br>';
}

</script>
</head>
<body>
<input type="checkbox" name="vehicle" value="Bike"> I have a bike<br>
<p onclick="zaza()">add</p>
</body>
</html>

3 个答案:

答案 0 :(得分:3)

问题是你压倒身体html:

document.body.innerHTML+=

而是尝试将复选框附加到正文。

function zaza() {
  var div = document.createElement('div');
  div.innerHTML = '<input type="checkbox" name="vehicle" value="Bike"> I have a bike<br>';
  document.body.appendChild(div);
}
p {
  cursor: pointer;
}
<input type="checkbox" name="vehicle" value="Bike">I have a bike
<br>
<p onclick="zaza()">add</p>

您也可以选择文档片段:

function zaza() {
  var child = document.createDocumentFragment();
  var tmp = document.createElement('input');
  tmp.type = 'checkbox';
  tmp.name = 'vehicle';
  tmp.value = 'Bike';
  child.appendChild(tmp);
  child.appendChild(document.createTextNode('I have a bike'));
  child.appendChild(document.createElement('br'));
  document.body.appendChild(child);
}
p {
  cursor: pointer;
}
<input type="checkbox" name="vehicle" value="Bike">I have a bike
<br>
<p onclick="zaza()">add</p>

答案 1 :(得分:0)

您正在添加具有相同名称的复选框,您必须为每个复选框指定不同的名称

答案 2 :(得分:0)

你需要创建元素并附加在正文中

function zaza() {
    var answer = document.createElement('input');
    answer.setAttribute('type', 'checkbox');
    answer.setAttribute('id', 'answer');
    answer.setAttribute('value', 'a');
    var answerLabel = document.createElement('label');
    answerLabel.setAttribute('for', 'answer'); // this corresponds to the checkbox id
    answerLabel.appendChild(answer);
    answerLabel.appendChild(document.createTextNode(' I have a bike'));
    document.body.appendChild(answerLabel);
    linebreak = document.createElement("br");
    answerLabel.appendChild(linebreak);
}

DEMO