mercredi 24 décembre 2014

Show selected checkbox values using javascript

I have been trying to create checkboxes and show their values. When you try to select only one of them, it works. When you try to select more than one, it only shows the highest value selected. How can I show all the values of all selected checkboxes?


Here is the code so far:


Html:



<!doctype html>
<html>
<head>
<title>Javascript checkboxes in real time</title>
<link rel = "stylesheet" href = "css/default.css">
</head>
<body>
<form action = "" method = "post">
<input type="checkbox" id = "1" value = "1">1<br>
<input type="checkbox" id = "2" value = "2">2<br>
<input type="checkbox" id = "3" value = "3">3<br>
<input type="checkbox" id = "4" value = "4">4<br>
<input type="checkbox" id = "5" value = "5">5<br>
</form>
<section></section>
<script src = "js/default.js"></script>
</body>
</html>


Javascript:



var checkbox = document.getElementsByTagName('input');
var section = document.getElementsByTagName('section');

setInterval(function(){
for(var i = 0; i <= checkbox.length - 1; i++){
if(checkbox[i].checked){
section[0].innerHTML = checkbox[i].value;
break;
}
else{
section[0].innerHTML = null;
}
}
}, 10);




Aucun commentaire:

Enregistrer un commentaire