1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125
| <!DOCTYPE html>
<html lang=fr>
<head>
<meta charset=utf-8>
<title>Générer un tableau à partir de cases à cocher</title>
<style>
form { margin: 1em; }
table { border-collapse: collapse; }
th { background: silver; }
th, td { padding: 0.25em 1em;
border: solid thin gray; }
td:empty { border: none; }
input[type=text] { border: solid thin silver;
border-radius: 2px;
box-shadow: inset 1px 1px 2px -1px #999;
color: black;
background: white; }
</style>
<script> 'use strict';
// polyfill léger pour Array.forEach
if (!('forEach' in Array)) {
Array.forEach = function(iterable, callback, context) {
Array.prototype.forEach.call(iterable, callback, context);
};
}
function updateTable() {
var $container = document.getElementById('table-container');
$container.innerHTML = '';
// voilà une manière plus propre d'écrire des tableaux
var $table = document.createElement('table');
// produits
var nProduits = 0;
var $headRow = $table.createTHead().insertRow(-1);
$headRow.insertCell(-1);
Array.forEach(
document.querySelectorAll('input[name="produit[]"]'),
function($input) {
if (!$input.checked) return;
nProduits++;
var $th = document.createElement('th');
$th.textContent = $input.value;
$headRow.appendChild($th);
}
);
// marques
var nMarques = 0;
var $tbody = $table.createTBody();
Array.forEach(
document.querySelectorAll('input[name="marque[]"]'),
function($input) {
if (!$input.checked) return;
nMarques++;
var $row = $tbody.insertRow(-1);
var $th = document.createElement('th');
$th.textContent = $input.value;
$row.appendChild($th);
var $text = document.createElement('input');
$text.type = 'text';
$text.placeholder = 'À compléter
';
for (var i = 0; i < nProduits; i++) {
$row.insertCell(-1).appendChild($text.cloneNode());
}
}
);
$container.appendChild($table);
}
document.addEventListener('DOMContentLoaded', function() {
updateTable();
document.addEventListener('change', function(changeEvent) {
var $target = changeEvent.target;
if ('INPUT' === $target.tagName && 'checkbox' === $target.type) {
updateTable();
}
});
});
</script>
</head>
<body>
<form>
<section>
<h2>Les marques</h2>
<label>
<input type="checkbox" name="marque[]" value="kinder" />
Kinder
</label>
<label>
<input type="checkbox" name="marque[]" value="milka" />
Milka
</label>
</section>
<section>
<h2>Les produits</h2>
<label>
<input type="checkbox" name="produit[]" value="bonbon" />
Bonbon
</label>
<label>
<input type="checkbox" name="produit[]" value="chocolat" />
Chocolat
</label>
</section>
</form>
<section id="table-container"></section>
</body>
</html> |
Partager