Ir para conteúdo
Fórum Script Brasil
  • 0

Adicionar Um Campo Ao Formulário Ao Clicar Num Link


Beraldo

Pergunta

Preciso fazer com que, ao se clicar num link, adicione um campo ao formulário.

Estou fazendo uns testes aqui, mas estou com um pouco de dificuldade.

Atualmente o código para teste está assim:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script language="javascript" type="text/javascript">
function campo(){
        var x = 3;
        if (x <= 10){
          document.write ("<label for='op_"+x+"'>Op&ccedil;&atilde;o 0"+x+": </label><input type='text' name='opcaoes' id='op_"+x+"' maxlength='100' /><br />");
         x++; 
            }
    }
</script>
<title>Testes</title>
</head>
<body>
<form name="enquete" id="enquete" method="post" action="enquete.php">
<label for="titulo">T&iacute;tulo: </label>
<input type="text" name="titulo" id="titulo" maxlength="100" /><br />
<label for="pergunta">Pergunta: </label>
<input type="text" name="pergunta" id="pergunta" maxlength="100" /><br /><br />

<label for="op_01">Op&ccedil;&atilde;o 01: </label>
<input type="text" name="opcoes" id="op_01" maxlength="100" /><br />
<label for="op_02">Op&ccedil;&atilde;o 02: </label>
<input type="text" name="opcoes" id="op_02" maxlength="100" /><br />

<a href="java script: void(0);" onclick="campo();">Adicionar mais uma op&ccedil;&atilde;o</a><br /><br />
<input type="submit" value="Criar Enquete" />
</form>
</body>
</html>

Quero que o novo campo apareça a cima do link, mas, para isso, não posso usar o document.write(). Como posso fazer isso?

O que pensei em fazer foi colocar uma div a cima do link, para fazer os novos campos apareceram dentro dela, mas como posso fazer com que os campos sejam exibidos dentro dessa div? Com que função?

Valeu

Abraços

Link para o comentário
Compartilhar em outros sites

12 respostass a esta questão

Posts Recomendados

  • 0
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title>

<script>

   function novoCampo(){
   
      var bloco = document.getElementById( "novo" );
      var modo  = bloco.style.display;
   
      if( modo == "none" ){
         bloco.style.display = "block";      
      }else{
         bloco.style.display = "none";
      } 
   
   }

</script>

</head>

<body>

<table width="100%" border="1" cellspacing="0" cellpadding="0">
  <tr>
    <td width="9%">Nome</td>
    <td width="91%"><label>
      <input type="text" name="textfield" /></label>
       <a href="#" onclick="java script:novoCampo();">
       novo campo
       </a> </td>
  </tr>
  <tr>
    <td>Email</td>
    <td><input type="text" name="textfield2" /></td>
  </tr>  
</table>


<div style="display:none" id="novo">

<table width="100%" border="1" cellspacing="0" cellpadding="0">
  <tr>
    <td width="9%">Novo</td>
    <td width="91%"><label>
      <input type="text" name="textfield3" />
    </label></td>
  </tr>  
</table>

</div>

</body>
</html>

Link para o comentário
Compartilhar em outros sites

  • 0

Não funcionou e, além disso, não é assim que quero.

Eu coloquei duas opções como o mínimo de opções, mas o máximo de opções é dez. Conforme o usuário clicar em "Nova opção", aparecerá mais um campo abaixo do último campo de texto, com o respectivo texto e id. Então não adianta colocar os campos dentro de uma div e mexer no display.

Link para o comentário
Compartilhar em outros sites

  • 0

Então veja se é assim :

<html>

<head>

<title>

</title>

<script>

function geraCampo(valor){

var bloco = document.getElementById('campo');

var txt = "<table border='0' width='60%'>";

for(i=0; i <= valor; i++ ){

txt += "<tr><td>Campo"+i;

txt += " <input type='text' name='campo'"+i+"></td><tr>";

bloco.innerHTML = txt;

}

}

</script>

</head>

<body>

<a href="#" onClick="java script:geraCampo(5);">

Campos novos

</a>

<span id="campo"></span>

</body>

</html>

Link para o comentário
Compartilhar em outros sites

  • 0

Esse esta mais legal

<html>

<head>

<title>

</title>

<script>

function geraCampo(valor){

var bloco = document.getElementById('campo');

var txt = "<table border='0' width='60%'>";

for(i=1; i <= valor; i++ ){

txt += "<tr><td>Campo"+i;

txt += " <input type='text' name='campo"+i+"'></td><tr>";

bloco.innerHTML = txt;

}

}

function mostraCaixa(){

var bloco = document.getElementById('qtde');

var modo = bloco.style.display;

if(modo == 'none'){

bloco.style.display = 'block';

}else{

bloco.style.display = 'none';

}

}

</script>

</head>

<body>

<a href="#" onClick="java script:mostraCaixa();">

+ Adicionar Campos novos

</a>

<div id='qtde' style="display:none">

<table border='0' cellpadding='0' cellspacing='0' width='25%'>

<tr>

<td>Quantidade</td>

<td><input type='text' size='3' value='' onblur="java script:geraCampo(this.value);"></td>

</tr>

</table>

</div>

<form method="post" action="teste.php">

<span id="campo"></span>

<input type="submit">

</form>

</body>

</html>

Link para o comentário
Compartilhar em outros sites

  • 0

olha este exemplo aí:

<HTML>
<HEAD>
<script>
function createRadioButton(){
    // Create radio button object with value="First Choice" and then insert 
    // this element into the document hierarchy.
    var newRadioButton = document.createElement("<INPUT TYPE='RADIO' NAME='RADIOTEST' VALUE='First Choice'>")
    document.body.insertBefore(newRadioButton);
    // Create radio button object with value="Second Choice" and then insert 
    // this element into the document hierarchy. 
    newRadioButton = document.createElement("<INPUT TYPE='RADIO' NAME='RADIOTEST' VALUE='Second Choice'>")
    document.body.insertBefore(newRadioButton);
}
</SCRIPT>
</HEAD>

<BODY>
<INPUT TYPE="BUTTON" ONCLICK="createRadioButton()" VALUE="Create two Radio Buttons"><BR>

<INPUT TYPE="BUTTON" ONCLICK="alert ( document.body.outerHTML )" VALUE="Click here to see HTML">

<BODY>
</HTML>

fonte: http://msdn.microsoft.com/workshop/author/...eateelement.asp

Link para o comentário
Compartilhar em outros sites

  • 0

Estou quase lá. :)

Olhem como está o código atual:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script language="javascript" type="text/javascript">
i = 3;
function campo() {
     if (i <= 10){ 
        //cria  campo de texto
    var y = 'Op&ccedil;&atilde;o 0'+i+': ';
    var x = document.createElement('input');

        //cria uma linha, pular pra linha de baixo
    var pula = document.createElement('br');

        //atributos do campo texto
    x.setAttribute('type', 'text');
    x.setAttribute('name', 'opcoes');
    x.setAttribute('id', 'op_'+x);
    x.setAttribute('maxlength', '100');

        //coloca a linha e o campo texto dentro da div
    document.getElementById('opcoes').appendChild(pula);
    document.getElementById('opcoes').appendChild(x);
    i = i+1;
    }
}
</script>
<title>Beraldo</title>
</head>
<body>
<form name="enquete" id="enquete" method="post" action="enquete.php">
<label for="titulo">T&iacute;tulo: </label>
<input type="text" name="titulo" id="titulo" maxlength="100" /><br />
<label for="pergunta">Pergunta: </label>
<input type="text" name="pergunta" id="pergunta" maxlength="100" /><br /><br />

<label for="op_01">Op&ccedil;&atilde;o 01: </label>
<input type="text" name="opcoes" id="op_01" maxlength="100" /><br />
<label for="op_02">Op&ccedil;&atilde;o 02: </label>
<input type="text" name="opcoes" id="op_02" maxlength="100" /><br />
<div id="opcoes">
</div>
<a href="java script: void(0);" onclick="campo();">Adicionar mais uma op&ccedil;&atilde;o</a><br /><br />
<input type="submit" value="Criar Enquete" />
</form>
</body>
</html>
O único problema está sendo inserir a variável y entre pula e x. Tentei assim:
document.getElementById('opcoes').appendChild(pula);
document.getElementById('opcoes').appendChild(y);
document.getElementById('opcoes').appendChild(x);

Mas assim o script não funciona. Como posso fazer?

Link para o comentário
Compartilhar em outros sites

  • 0

Olá Beraldo.

Procure no seu código JS implantar o innerHTML. Ele tem a função de acrescentar qualquer elemento no final de um objeto.

Não intendi o porque de colocar x++. Poderíamos utiliza-lo caso você estivesse trabalhando com laços de repetição.

Abraços :D

Link para o comentário
Compartilhar em outros sites

  • 0

Procure no seu código JS implantar o innerHTML. Ele tem a função de acrescentar qualquer elemento no final de um objeto.

No código que postei a cima onde posso usar o innerHTML? Pelo que entendi, o innerHTML insere códigos, certo? Eu só quero adicionar o conteúdo da variável y.

Não intendi o porque de colocar x++. Poderíamos utiliza-lo caso você estivesse trabalhando com laços de repetição.

Eu coloquei errado. :ph34r:

É i = i + 1.

* A enquete poderá ter no máximo 10 opções.

Link para o comentário
Compartilhar em outros sites

  • 0

Achei uma forma melhor de se fazer o que quero. Achei que ficou melhor.

Caso alguém queira saber como ficou, aqui vai o código.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script language="javascript" type="text/javascript">
function campo(select) {
 var x = select.options[select.selectedIndex].value;
 var div = document.getElementById('opcoes');
 var campo = '';
     for (a = 1; a <= x; a++){
       campo += "Op&ccedil;&atilde;o "+a+": <input type='text' name='opcoes' /><br />";    
       div.innerHTML = campo;
     }
}
</script>
<title>Teste</title>
</head>
<body>
<form name="enquete" id="enquete" method="post" action="enquete.php">
<label for="titulo">T&iacute;tulo: </label>
<input type="text" name="titulo" id="titulo" maxlength="100" /><br />
<label for="pergunta">Pergunta: </label>
<input type="text" name="pergunta" id="pergunta" maxlength="100" /><br /><br />

N&uacute;mero de op&ccedil;&otilde;es da enquete: 
<select name="n_opcoes" onchange="campo(this)">
  <option value="2">2</option>
  <option value="3">3</option>
  <option value="4">4</option>
  <option value="5">5</option>
  <option value="6">6</option>
  <option value="7">7</option>
  <option value="8">8</option>
  <option value="9">9</option>
  <option value="10">10</option>
</select><br /><br />

<div id="opcoes">
</div>
<br />
<input type="submit" value="Criar Enquete" />
</form>
</body>
</html>

Agradeço muito a ajuda de todos. :)

Abraços

Link para o comentário
Compartilhar em outros sites

Visitante
Este tópico está impedido de receber novos posts.


  • Estatísticas dos Fóruns

    • Tópicos
      152,1k
    • Posts
      651,9k
×
×
  • Criar Novo...