Adding a new checkbox makes the other checkboxes unchecked

157 Views Asked by At

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

There are 3 best solutions below

1
On BEST ANSWER

Problem is your overriding the body 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>

0
On

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

0
On

You are adding checkbox with the same name, you have to give every checkbox different name