简体   繁体   English

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

[英]Adding a new checkbox makes the other checkboxes unchecked

When I add a new checkbox, old checkboxes are set unchecked (even when they were checked). 当我添加新复选框时,会将旧复选框设置为未选中状态(即使已选中)。 How can I solve it? 我该如何解决?

Here there is my code: 这是我的代码:

<%@ 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>

Problem is your overriding the body html: 问题是您重写正文html:

document.body.innerHTML+=

Instead try appending the checkbox to body. 而是尝试将复选框附加到正文。

 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> 

You may also go for document fragment: 您也可以使用文档片段:

 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> 

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

you need to create elements and append in the body 您需要创建元素并追加到正文中

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 演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM