Create dynamic checkbox using JavaScript

1

I have a form. When I press the Send button, the function checks the information.

If everything is ok, I would like to make a stuffed checkbox table.

The table would have (arrows) rows and (rels + cycles) columns. In each cell, I would like to place the checkbox.

Unfortunately, I tried some posts and I did not succeed. Every help is welcome. Many thanks!

function Enviar() { 
	var flechas = document.getElementById("flechasid");
	var rels = document.getElementById("relsid");  
	var ciclos = document.getElementById("ciclosid"); 
	if (flechas.value > 0 && flechas.value < 30 && ciclos.value > 0 && ciclos.value < 10 && rels.value > 0 && rels.value < 20) { 
		alert('Os seus dados foram encaminhados com sucesso!');
        } else {
		alert('Informações inválidas!');
	};
} 
<!DOCTYPE html>
 
<html>
<head>
<meta name="description" content="Aprenda a criar PHIAs">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"> 
</head>

<body>
<script src="app.js"></script>
<form name="Untitled-2">
	<fieldset>
		<legend>
			Número de relações do tipo 3		
		</legend>
			<table cellspacing="3">
  				<tr>
   				<td>
    					<label for="rels">
    						Relações
    					</label>
   				</td>
   				<td align="left">
    					<input type="text" name="rels" id="relsid" required="required" placeholder=0>
					</td>
				</tr>
			</table>
	</fieldset>
	<fieldset>
		<legend>
			Número de flechas nessas relações		
		</legend>
			<table cellspacing="3">
  				<tr>
   				<td>
    					<label for="flechas">
    						Flechas
    					</label>
   				</td>
   				<td align="left">
    					<input type="text" name="flechas" id="flechasid" required="required" placeholder=0>
					</td>
				</tr>
				
			</table>
	</fieldset>
	<fieldset>
		<legend>
			Número de ciclos elementares		
		</legend>
			<table cellspacing="3">
  				<tr>
   				<td>
    					<label for="ciclos">
    						Ciclos
    					</label>
   				</td>
   				<td align="left">
    					<input type="text" name="ciclos" id="ciclosid" required="required" placeholder=0>
					</td>
				</tr>
			</table>
	</fieldset>

	<input type="button" onclick="Enviar();" value="Enviar">
	<input type="reset" value="Limpar">
</form>

<div id="test"></div>

</body>
</html>
    
asked by anonymous 14.07.2015 / 05:26

1 answer

2

How to create a table in JavaScript?

Structured data

Ideally you should have some object or array with the table structure and data.

For example if each line is the ID of a relation and each cell has a name you could have something like this:

// exemplo A
var data = [{
    idLinha1: [{
        isRelacao: 'r1'
    }, {
        idFlecha: 'f1'
    }, {
        idCiclo: 'c1'
    }],
    idLinha2: [{
        isRelacao: 'r2'
    }, {
        idFlecha: 'f2'
    }, {
        idCiclo: 'c2'
    }],
    // etc...

If you do not need IDs for each cell you can do something simpler like this:

// exemplo B
var data = {
    celulas: ['relacao', 'flecha', 'ciclo'],
    idLinhas: ['linha1', 'linha2', 'linha3', ...etc ]
}

Two important things to keep in mind:

  • Think about how you want to use the data later, creating the right HTML makes it much easier when it's time to extract information
  • Arrays respect order, objects do not. If it is important the order of the rows is an array and not an object key.

How to create the elements

Each element must be created with document.createElement() where you pass the tag name to the native method.

An example for example B would be

var table = document.createElement('table');

// cabeçalho da table
var tr = document.createElement('tr');
var th = document.createElement('th');
tr.appendChild(th); // vazia
data.celulas.forEach(function (celula) { // Nota "a)"
    var th = document.createElement('th');
    th.innerHTML = celula;
    tr.appendChild(th);
});
table.appendChild(tr);

// corpo
data.idLinhas.forEach(function (id) {
    // criar nova linha
    var tr = document.createElement('tr');
    tr.dataset.id = id;
    // primeira célula com nome da linha
    var td = document.createElement('td');
    td.innerHTML = id;
    tr.appendChild(td);
    // percorrer array de TDs
    data.celulas.forEach(function (celula) {
        var td = document.createElement('td');
        var input = document.createElement('input');
        input.type = 'checkbox';
        input.name = celula + []; // * - Nota "b)"
        td.appendChild(input);
        tr.appendChild(td);
    });
    table.appendChild(tr);
});
// adicionar tabela ao documento
document.body.appendChild(table);

jsFiddle: link

Notes:

a) What does data.celulas.forEach(function (celula) {}); ?

This line is for creating the title of the columns. data.celulas is an array that has the names that should be at the top of each column. .forEach() is a native array method for traversing the array element by element. So by passing it a function it will make each element available, in the celula variable.

b) - I used [] because if you send it to the server it will treat inputs with the same name as an array.

    
14.07.2015 / 07:56