Create dynamic checkbox using Javascript

Asked

Viewed 1,778 times

1

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

In case everything is ok, I would like to make a checkbox packed table.

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

Unfortunately, I tried a few posts and did not succeed. Any help is welcome. Thank you very much!

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>

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 row 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 don’t need Ids for each cell you can do something simple like this:

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

Two important things to consider:

  • think how you want to use the data later, creating the right HTML makes it much easier when it’s time to remove information
  • Arrays respect order, objects do not. If it is important to order the lines iterate an array and not object keys.

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: http://jsfiddle.net/oyt94rek/

Notes:

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

This row is for creating column title content. 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 running the array element by element. Thus passing you a function it will make available each element, in the variable celula.

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

  • 1

    Thank you @Sergio . I’m new to programming but managed to implement your response to my situation. I don’t know if I’m going to need further to understand the syntax of data.celulas.forEach(function (celula) {});, So far it worked. I had to have written what I’m going to do with the table. But you got it right, I’ll create another function using the information from each cell. So I need a name for each cell according to the table position. A detail, any hint in the question title is welcome.

  • @Vasco joined explanation about data.celulas.forEach(function (celula) {});. I’m glad I could help.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.