Skip to content

Instantly share code, notes, and snippets.

@carloscarucce
Last active November 24, 2022 12:58
Show Gist options
  • Save carloscarucce/f0b68c63e2e4a86aab8c933f539fb09c to your computer and use it in GitHub Desktop.
Save carloscarucce/f0b68c63e2e4a86aab8c933f539fb09c to your computer and use it in GitHub Desktop.
Exemplo de tabela dinamica (Javascript)
<!DOCTYPE html>
<html>
<head>
<title>Exemplo Ajax</title>
</head>
<body>
<form action="{{ url('salvar') }}" method="post">
@csrf
<button type="button" id="btn_add">Adicionar</button>
<table id="partes">
<tr>
<th>Nome</th>
<th colspan="2">Sexo</th>
</tr>
</table>
<button type="submit">SALVAR</button>
</form>
<script>
const partes = document.getElementById('partes');
let indice = 0;
function criarLinha (nome, sexo) {
if ((partes.querySelectorAll('tr').length - 1) >= 10) {
alert('Não pode');
return;
}
let linha = document.createElement('tr');
let coluna1 = document.createElement('td');
let coluna2 = document.createElement('td');
let coluna3 = document.createElement('td');
let inputNome = document.createElement('input');
inputNome.setAttribute('type', 'text');
inputNome.setAttribute('name', 'pessoas['+indice+'][nome]');
coluna1.append(inputNome);
linha.append(coluna1);
let selectSexo = document.createElement('select');
selectSexo.setAttribute('name', 'pessoas['+indice+'][sexo]');
let options = {"m": "Masculino", "f": "Feminino"};
for (let i in options) {
let option = document.createElement('option');
option.setAttribute('value', i);
option.innerText = options[i];
selectSexo.append(option);
}
coluna2.append(selectSexo);
linha.append(coluna2);
let btn = document.createElement('button');
btn.setAttribute('class', 'remove');
btn.innerText = "X";
coluna3.append(btn);
linha.append(coluna3);
btn.onclick = function() {
linha.remove();
};
if (nome) {
inputNome.value = nome;
}
if (sexo) {
selectSexo.value = sexo;
}
indice++;
partes.append(linha);
}
document.getElementById('btn_add').onclick = function(){
criarLinha(null, null);
};
@forelse($pessoas as $pessoa)
criarLinha('{{ $pessoa['nome'] }}', '{{ $pessoa['sexo'] }}');
@empty
criarLinha(null, null);
@endforelse
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment