Criar Elementos Novos Através De Javascript
#1
Posted 28/06/2006, 05:10
Por exemplo, tenho um formulário com 5 inputs. Aí tem um link embaixo deles: "Para adicionar mais uma opção, clique aqui."
E essim que esse link fosse clicado, um novo input seria criado e inserido no formulário.
Meu conhecimento em javascript é básico, alguém conhece algum guia ou forma de fazer isso?
[]'s
#3
Posted 03/07/2006, 14:49
Mas infelizmente não deu certo ao inserir em um formulário:
<html>
<head>
<title>||Working with elements||</title>
</head>
<script language="javascript">
var mydiv = false;
var div = false;
function init(){
mydiv = document.getElementById("Mydiv");
div = document.createElement("div");
document.body.insertBefore(div, mydiv);
div.innerHTML = "<h1>Hi there!</h1>";
}
</script>
<body>
<form name="formulario" method="post" action="index.php?area=Teste">
<input id="InputMarcador" size="30">
<input type="button" onClick="init()" value="Criar">
<div id='Mydiv'> The text above has been created dynamically </div>
<input size="30">
</form>
</body>
</html>Tudo o que eu fiz foi criar um formulário e inserir o código dentro dele, mas não deu certo. Fora do form, funciona.
A idéia é criar mais inputs pro formulário.
Se desse para destruir também... existe como?
Outra coisa, ele usa um insertBefore para inserir o div. Eu tentei insertAfter para inserir após mas só funcionou o insertBefore.
#4
Posted 03/07/2006, 16:34
<script type="text/javascript">
var id = 1;
function novoCampo(){
var inp = document.createElement("input");
inp.setAttribute("id", id );
var lab = document.createElement("label");
lab.setAttribute("id", "l"+id);
var lab_content = document.createTextNode("Campo de Texto " + id + " ");
var quebra = document.createElement("br");
lab.appendChild(lab_content);
var inpP = document.getElementById(id-1);
var parentInp = inpP.parentNode;
parentInp.insertBefore(lab, inpP.nextSibling);
parentInp.insertBefore(inp, lab.nextSibling);
parentInp.insertBefore(quebra, lab);
++id;
}
</script>
</head>
<body>
<form name="form1" method="post" action="">
<label id="l0">Campo de Texto 0</label>
<input type="text" name="textfield" id="0"><br />
<input type="submit" name="Submit" value="+ 1 Campo" onClick="novoCampo();return false;">
</form>

Yeah I do have some stories, and it's true I want all the glory ...
#5
Posted 04/07/2006, 17:04
<input type="hidden" name="item_id_2" value="0002"> <input type="hidden" name="item_descr_2" value=" _"> <input type="hidden" name="item_quant_2" value="1"> <input type="hidden" name="item_valor_2" value="001"> <input type="hidden" name="item_frete_2" value="0"> <input type="hidden" name="item_peso_2" value="0>
Não entendi muito bem o código, tem como vc passar 1 exemplo de como criar 1 ou se possivel vários inputs hidden?
#6
Posted 04/07/2006, 18:15

Yeah I do have some stories, and it's true I want all the glory ...
#7
Posted 04/07/2006, 18:20
#8
Posted 04/07/2006, 19:04
inp.setAttribute("id", "field01" );
inp.setAttribute("type", "hidden" );
etc..
Só ir acrescentando os atributos. Como você já imprimiu a referência é só ir fazendo a leitura que fica super fácil de entender.

Yeah I do have some stories, and it's true I want all the glory ...
#9
Posted 04/07/2006, 21:15
<script type="text/javascript">
function novoCampo()
{
var inp = document.createElement("input");
inp.setAttribute("id", "item_id_1");
inp.setAttribute("type", "text");
inp.setAttribute("name", "item_id_1");
//
var inp1 = document.createElement("input");
inp1.setAttribute("id", "item_descr_1");
inp1.setAttribute("type", "text");
inp1.setAttribute("name", "item_descr_1");
//
var inp2 = document.createElement("input");
inp2.setAttribute("id", "item_quant_1");
inp2.setAttribute("type", "text");
inp2.setAttribute("name", "item_quant_1");
//
var inp3 = document.createElement("input");
inp3.setAttribute("id", "item_valor_1");
inp3.setAttribute("type", "text");
inp3.setAttribute("name", "item_valor_1");
//
var inpP = document.getElementById("item_id_1");
var parentInp = inpP.parentNode;
parentInp.insertBefore(inp, nextSibling);
}
</script>
</head><body onLoad="novoCampo()"> Não funcionou, me exibe uma mensagem de objeto necessário. sabe o que pode ta errado?
#10
Posted 05/07/2006, 08:59
<script type="text/javascript">
function insere(){
var inp = document.createElement("input");
inp.setAttribute("id", "item_id_1");
inp.setAttribute("type", "text");
inp.setAttribute("name", "item_id_1");
var pai = document.getElementById("form1");
pai.appendChild(inp);
}
</script>
<form name="form1" id="form1" action="" onSubmit="return false;">
<input type="submit" name="submit" value="inserir" onClick="insere();">
</form>
O método appendChild vai inserir um Node a lista de children do parent !!
Em outras palavras, imagine o formulário como o pai(parent) e o input como o filho(children), a função acima vai inserir um childNode no parent especificado. Aqui eu usei o appendChild, mas se você testar o exemplo vai notar o porque de ter usado o insertBefore no outro exemplo.
Referência: http://developer.moz...ent.appendChild

Yeah I do have some stories, and it's true I want all the glory ...
#11
Posted 05/07/2006, 09:19
Para quem precisar, achei uma versão traduzida: http://www.amtechs.c.../def-index.html
#12
Posted 07/07/2006, 21:27
Li as referências e estudei o código, aí surgiram algumas dúvidas:
- quando eu coloco VAR antes de uma linha da função, o valor da variável é retornado? Ou é só uma atribuição?
- Essa parte aqui:
var parentInp = inpP.parentNode; parentInp.insertBefore(lab, inpP.nextSibling); parentInp.insertBefore(inp, lab.nextSibling); parentInp.insertBefore(quebra, lab);
É uma lista?
- Caso seja uma lista, então tem como eu apontar o último nó para "lixo" (nil), se eu quiser apagar um input criado? Caso não, como eu faço para apagar o último input criado?
- Sem querer explorar com várias perguntas, mas vc me recomenda um livro sobre DOM? Eu realmente estou gostando disso!
mais uma vez, valeu!
[]'s
Edição feita por: FelipeBSR, 07/07/2006, 21:29.
#13
Posted 08/07/2006, 06:57
Para pegar a última criança (filho hahaha), é só usar .lastChild.
http://developer.moz...ement.lastChild
E sobre o livro, já li e recomendo com grande prazer:
http://www.sitepoint.com/books/dhtml1/
#14
Posted 10/07/2006, 19:15
Eu tentei de diversas formas remover o último input acrescentado e não consegui. Procurei guias e mais guias, mas não sei onde estou errando:
function deletaCampo() {
var d = document.lastChild;
removeChild(d);
}
#15
Posted 12/07/2006, 13:56
function deletaCampo() {
var d = document.GetElementById("form").lastChild;
removeChild(d);
}

Yeah I do have some stories, and it's true I want all the glory ...
1 user(s) are reading this topic
0 membro(s), 1 visitante(s) e 0 membros anônimo(s)










