[JavaScript] Adicionar/remover linhas a tabela em run-time

Armadillo

Folding Member
Código:
<HTML>
<head>
<title>Encomendas</title>
<meta http-equiv="Content-Language" content="pt">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript" language="javascript">

function GerarPrecoLiq()
{

}


function removeItem(linha)
{
var tbl = document.getElementById('items_enc');
tbl.deleteRow(linha);
}


function AddItem()
{

var produto =form_add.TextProduto.value;            //adquirir id produto
var descricao=form_add.TextDescri.value;            //adquirir descricai produto
var preco=form_add.TextPreco.value;                    //adquirir pvp produto
var desconto=form_add.TextDesc.value;                //adquirir desc produto
var quantidade=form_add.TextQuant.value;            //adquirir qtd produto



var tbl = document.getElementById('items_enc');        //adquirir tabela de encomenda
var lastRow = tbl.rows.length;                        //adquirir n.o de linhas
var iteration = lastRow+1;
var row = tbl.insertRow(lastRow);

// A D I C I O N A R   L I N H A S

// celula produto
var cellProd = row.insertCell(0);
var pd = document.createElement('input');
pd.type = 'text';
pd.name = 'txtProd' + iteration;
pd.id = 'txtProd' + iteration;
pd.width = '150px';
pd.value = produto;
pd.readOnly = true;
cellProd .appendChild(pd);


// celula descricao
var cellDescr = row.insertCell(1);
var dcr = document.createElement('input');
dcr.type = 'text';
dcr.name = 'txtDescri'  + iteration;
dcr.id = 'txtDescri' + iteration;
dcr.width = '100%';
dcr.value=descricao;                
cellDescr .appendChild(dcr);        //adicionar á tabela

// celula preco
var cellPreco = row.insertCell(2);
var pvp = document.createElement('input');
pvp.type = 'text';
pvp.name = 'txtPVP'  + iteration;
pvp.id = 'txtPVP' + iteration;
pvp.width = '65px';
pvp.value=preco;
cellPreco.appendChild(pvp);        //adicionar á tabela

// celula desconto
var cellDesconto = row.insertCell(3);
var dct = document.createElement('input');
dct.type = 'text';
dct.name = 'txtDct'  + iteration;
dct.id = 'txtDct' + iteration;
dct.width= '65px';
dct.value=desconto;
cellDesconto.appendChild(dct);        //adicionar á tabela

// celula quantidade
var cellQtd = row.insertCell(4);
var qtd = document.createElement('input');
qtd.type = 'text';
qtd.name = 'txtQtd'  + iteration;
qtd.id = 'txtQtd' + iteration;
qtd.width= '65px';
qtd.value=quantidade;
cellQtd.appendChild(qtd);        //adicionar á tabela


// celula total linha
var cellTotalLinha = row.insertCell(5);
var TtL = document.createElement('input');
TtL.type = 'text';
TtL.name = 'txtDct'  + iteration;
TtL.id = 'txtDct' + iteration;
//Del.width = '65px';
TtL.value=quantidade * (preco);
cellTotalLinha.appendChild(TtL);        //adicionar á tabela


// celula eliminar item
var cellDelLinha = row.insertCell(6);
var Del = document.createElement('input');
Del.type = 'button';
Del.name = 'btDel'  + iteration;
Del.id = 'btDel' + iteration;
Del.heigth = 100;
Del.width = 100;
//Del.onClick = removeItem(iteration);
cellDelLinha.appendChild(Del);        //adicionar á tabela


}
</script>

</head>
<body style="font-family:Verdana" >
    <form method="post">
        N.º Cliente <input name="Text1" type="text" style="WIDTH: 100px">&nbsp; <input name="Submit2" type="submit" value="OK" style="WIDTH: 75px">&nbsp;
        <input name="Text1" type="text" value="nome_cli" style="WIDTH: 455px" readonly><br>
    </form>
    <div id="div_items_existentes">
        <strong>Produtos em encomenda</strong></div>
    <form id="form_encomenda" method="post" action="">
        <table id="items_enc" style="WIDTH: 100%" >
            <tr>
                <td width="150">Produto</td>
                <td>Descrição</td>
                <td width="65">Preço</td>
                <td width="65">Desconto</td>
                <td width="65">Quantidade</td>
                <td width="65">Total Linha</td>
                <td width="80">Acção</td>
            </tr>
        </table>
        <INPUT id="Submit1" type="submit" value="Concluir Encomenda" name="Submit1" onClick="RemoveItem()">
    </form>
    
    
    <form id="form_add" method="post" action="" style="BACKGROUND-COLOR:#e8ffe6">
        Adicionar items<br>
        <table style="WIDTH: 100%">
            <tr>
                <td width="150">Produto</td>
                <td>Descrição</td>
                <td width="65">Preço</td>
                <td width="65">Desconto</td>
                <td width="65">Quantidade</td>
                <td width="80"></td>
            </tr>
            <tr>
                <td><input name="TextProduto" type="text" style="WIDTH: 150px"></td>
                <td><input name="TextDescri" type="text" style="WIDTH: 100%"></td>
                <td><input name="TextPreco" type="text" style="WIDTH: 65px"></td>
                <td><input name="TextDesc" type="text" style="WIDTH: 65px"></td>
                <td><input name="TextQuant" type="text" style="WIDTH: 65px"></td>
                <td>
                    <input name="Submit3" type="button" value="adicionar" style="WIDTH: 80px" onClick="AddItem()"></td>
            </tr>
        </table>
    </form>
    </body>
</HTML>
Desculpem o tamanho do codigo mas assim ficam com tudo.
Problema 1: Isto nao funciona bem em IE7
Problema 2: como adicionar a acção de remover linha a um botao criado em runtime?

Esperando pela vossa ajuda
Obrigado
 
Última edição:
Boas..

O script nem em FF trabalha, só trabalha mesmo em IE6..

Tens aí 2 problemas graves, só à primeira vista:
- A página não é válida.
- Acedes às várias inputs através do formName.inputName.value e devias aceder por document.getElementById('id_da_input').

Primeiro que tudo, convém validares o documento.

A seguir o que te aconselho a fazer, é usares o document.getElemenById(), para saberes os vários valores das inputs.
Código:
//Por exemplo, saber o valor da input com o id xpto
var valor = document.getElementById('xpto');


Para apagares cada linha, podes fazer por exemplo:
Código:
        var cellDelLinha = row.insertCell(6);
	var Del = document.createElement('input');
	Del.type = 'button';
	Del.name = 'btDel'  + iteration;
	Del.id = 'btDel' + iteration;
	Del.heigth = 100;
	Del.width = 100;
	Del.onClick = function () { removeItem(this.parentNode.parentNode) };
	cellDelLinha.appendChild(Del);

E na função removeItem, tens o seguinte:
Código:
        function removeItem(line) {
              line.parentNode.removeChild(line);
        }

O parentNode, vai-te buscar o node anterior, no caso de ser aplicado ao botão, vai buscar uma TD primeiro, e depois a linha.

Na função removeItem, fazemos outra vez parentNode, para ir buscar o TBODY, e a seguir removes do TBODY a linha, usando o removeChild.

Espero ter ajudado, hasta all [[]]
 
Última edição:
Fiz as alterações a bold e funciona (remover linha) aqui no FF/Linux.
Código:
.......
function removeItem(linha) {
	var tbl = document.getElementById('items_enc');
[B]	var objLinha = linha.parentNode.parentNode;
	tbl.deleteRow(objLinha.rowIndex);[/B]
}
.......
	// celula eliminar item
	var cellDelLinha = row.insertCell(6);
	var Del = document.createElement('input');
	Del.type = 'button';
	Del.name = 'btDel'  + iteration;
	Del.id = 'btDel' + iteration;
	Del.heigth = 100;
	Del.width = 100;
[B]	Del.onclick = function() { removeItem(this) };[/B]
	cellDelLinha.appendChild(Del);        //adicionar á tabela
 
Back
Topo