Criar Elementos com Javascript

11 respostas
R

Galera sei pouco de Javascript estou esperando que vocês consigam me ajudar.
Tenho um form que tem DDD e Telefone 2 campos inputs, gostaria que vcs me ajudassem da seguinte forma
eu que cria um botão tipo link com a opção de mais para que quando o usuário clicar possa ser exibido mais inputs
e ele possa cadastrar no máximo 3 telefones.

Aqui o meu formulário:

<p>
  &lt;label for="ddd"&gt;DDD: &lt;/label&gt;
    &lt;input type="text" name="ddd" id="ddd" maxlength="2" onKeyPress="return txtBoxFormat(this, '99', event);" onChange="return txtBoxFormat(this, '9999-9999', event);" value="" /&gt;
			
  &lt;label for="tel" class="inline"&gt;Telefone: &lt;/label&gt;
    &lt;input type="text" name="tel" id="tel" maxlength="9" onKeyPress="return txtBoxFormat(this, '9999-9999', event);" onChange="return txtBoxFormat(this, '9999-9999', event);" value="" /&gt;
</p>

Por favor me ajudem.

11 Respostas

caarlos0

cria mais 3 campos, com um style=“display: none”,
dae quando clicar no link, faça $(’#tel2’).show(); (com o jQuery) ou document.getElementById(‘tel2’).style.display = ‘block’; ou document.getElementById(‘tel2’).style.display = ‘inline’;

:slight_smile:

R

Valeu Caarlos
Algo do tipo assim?

<p>  
      &lt;label for="ddd"&gt;DDD: &lt;/label&gt;  
        &lt;input type="text" name="ddd" id="ddd" maxlength="2" onKeyPress="return txtBoxFormat(this, '99', event);" onChange="return txtBoxFormat(this, '9999-9999', event);" value="" /&gt;  
                  
      &lt;label for="tel" class="inline"&gt;Telefone: &lt;/label&gt;  
        &lt;input type="text" name="tel" id="tel" maxlength="9" onKeyPress="return txtBoxFormat(this, '9999-9999', event);" onChange="return txtBoxFormat(this, '9999-9999', event);" value="" style="display: none"/&gt;  
		&lt;input type="text" name="tel1" id="tel1" maxlength="9" onKeyPress="return txtBoxFormat(this, '9999-9999', event);" onChange="return txtBoxFormat(this, '9999-9999', event);" value="" style="display: none"/&gt;  
		&lt;input type="text" name="tel2" id="tel2" maxlength="9" onKeyPress="return txtBoxFormat(this, '9999-9999', event);" onChange="return txtBoxFormat(this, '9999-9999', event);" value="" style="display: none"/&gt;  
    </p>  
	<a  >Adicionar item</a>

Ainda não resolvi.

caarlos0
<script language="text/javascript">
function adicionarNro()
{
var tel1 = $('#tel1');
var tel2 = $('#tel2');
if(tel1.css('display') != none)
{
tel1.show();
}
else if(tel2.css('display') != none)
{
tel2.show();
}
}
</script>

<p>  

      <label for="ddd">DDD: </label>  
        <input type="text" name="ddd" id="ddd" maxlength="2" onKeyPress="return txtBoxFormat(this, '99', event);" onChange="return txtBoxFormat(this, '9999-9999', event);" value="" />  
                  

<label for="tel" class="inline">Telefone: </label>  
<input type="text" name="tel" id="tel" maxlength="9" onKeyPress="return txtBoxFormat(this, '9999-9999', event);" onChange="return txtBoxFormat(this, '9999-9999', event);" value="" style="display: none"/>
<input type="text" name="tel1" id="tel1" maxlength="9" onKeyPress="return txtBoxFormat(this, '9999-9999', event);" onChange="return txtBoxFormat(this, '9999-9999', event);" value=""       style="display: none"/>  
<input type="text" name="tel2" id="tel2" maxlength="9" onKeyPress="return txtBoxFormat(this, '9999-9999', event);" onChange="return txtBoxFormat(this, '9999-9999', event);" value="" style="display: none"/>  
    </p>  
	<a  href="javascript:adicionarNro();">Adicionar item</a>

acho que algo assim vai funcionar.. não esqueça de incluir o jQuery na aplicação. Se estiver usando richfaces, substitua o "$" por "jQuery", senão conflita com o prototype.

R

Vlw cara mais ficou um pouco mai complicado porque uso ajax em box que abro
para cadastrar um funcionário.

Faço assim oh no arquivo comportamento.js:

jQuery(function($) {
    //Definindo quantos campos poderão ser criados (máximo);
var iCamposTotal = 2;
var iCampos = 1;
  $('input:text').live('focus',function() {
    $(this).select();
  });

  $('a#criarinput').live('click', function(e) {
    e.preventDefault();
    var $localPraIncluir = $(this).parent();
    /* usei o $ acima porque costumo o fazer quando
     * é pra identificar um objeto/coleção/elemento
     * jQuery
     */
    var table = ('&lt;tbody&gt;&lt;tr&gt;&lt;td&gt;&lt;div align="left"&gt;&lt;input type="text" name="ddd[]" id="ddd" maxlength="2" onKeyPress="return txtBoxFormat(this, "99", event);" onChange="return txtBoxFormat(this, "9999-9999", event);" value="" /&gt;&lt;/div&gt;&lt;/td&gt;');
        table += ('&lt;td&gt;&lt;input type="text" name="tel[]" id="tel" maxlength="9" onKeyPress="return txtBoxFormat(this, "9999-9999", event);" onChange="return txtBoxFormat(this, "9999-9999", event);" value="\"&gt;&lt;?php echo isset($_GET["\"editar\""]) ? $row_rsDadosEncontrados["\"chrTelefone\""] : ""; ?&gt;" /&gt;&lt;/td&gt;');
        table += ('&lt;td&gt;&lt;select name="intIdTipoTelefone[]" id="intIdTipoTelefone"&gt;&lt;option value="\"&gt;&lt;?php echo isset($_GET["\"editar\""]) ? $row_rsDadosEncontrados["\"intIdTipoTelefone\""] : ""; ?&gt;"&gt;&lt;?php echo isset($_GET["\"editar\""]) ? stripslashes(utf8_encode($row_rsDadosEncontrados["\"chrTipoTelefone\""])) : ""; ?&gt;&lt;/option&gt;&lt;/select&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/tbody&gt;');
    if (iCampos &lt;= iCamposTotal) {
    $(table).appendTo($localPraIncluir);
    iCampos++;
    }
    $localPraIncluir.find('input:text').last().focus();
  });
});

E o formulario está assim no meu formulário.php:

&lt;table width="100px;"&gt;
                        &lt;thead&gt;
				&lt;tr&gt;
                                    &lt;th&gt;&lt;div align="left"&gt;DDD: &nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Telefone: &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Tipo Telefone:&lt;/div&gt;<a  >mais tel!</a>&lt;/th&gt;
					&lt;!--
                                        &lt;th&gt;&lt;div align="left"&gt;Telefone:&lt;/div&gt;&lt;/th&gt;
					&lt;th&gt;&lt;div align="left"&gt;Tipo Telefone:&lt;/div&gt;&lt;/th&gt;
                                        --&gt;
                                &lt;/tr&gt;
                        &lt;/thead&gt;

            &lt;/table&gt;

vc já fez algo assim?
Tem que ser com ajax tipo eu colocaria os títulos com DDD TEL TIPO e abaixo iria gerar os campo já fez tem alguma idéia?

Se vc usar aí vc vai ver como está meu formulário.

caarlos0

ih cara, não manjo nada de php, não sei como faz pra ele conversar com o AJAX… no Richfaces isso é abstraido atraves da lib Ajax4JSF :stuck_out_tongue:

R

Vlw caarlos0
pela ajuda se alguém souber e puder ajudar.

caarlos0

mas de gambiarra eu manjo HAEUIAEIAE

talvez tu consiga salvar os dados em um array JS, e pegar eles depois… se eu entendi sua pergunta, e se você conseguir fazer isso, deve funcionar…

R

Vou tentar “gambiarrar” aqui vlw.

caarlos0

manolo, o seu problema com o ajax, são as tags do PHP ali, que quando inseridas por jQuery não funcionam né?

se for, faça isso diferente, coloque todos os campos diretamente no html, só que com display none, aí, você só precisa dar um show() neles… resolve o seu probleminha aí facinho =)

R

Alguém sabe concatenar aí, não estou conseguindo é php com javascript?

var table = ('<br /><table border="0"><tbody><tr><td style="width: 100px; border:none;"><div align="left"><input type="text" name="ddd[]" id="ddd" maxlength="2" onKeyPress="return txtBoxFormat(this, "99", event);" onChange="return txtBoxFormat(this, "9999-9999", event);" value=\"\" /></div></td>');

table += ('<td style="width: 310px; border:none;"><div align="left"><input type="text" name="tel[]" id="tel" maxlength="9" onKeyPress="return txtBoxFormat(this, \'9999-9999\', event);" onChange="return txtBoxFormat(this, \'9999-9999\', event);" value="\"<?php echo isset($_GET["\"editar\""]) ? $row_rsDadosEncontrados["\"chrTelefone\""] :  \'\'; ?>"\" /></div></td>');

table += ('<td style="border:none;"><div align="left"><select name="intIdTipoTelefone[]" id="intIdTipoTelefone"><option value="<?php echo isset($_GET[\'editar\']) ? $row_rsDadosEncontrados[\'intIdTipoTelefone\'] : \'\'; ?>"><?php echo isset($_GET[\'editar\']) ? stripslashes(utf8_encode($row_rsDadosEncontrados[\'chrTipoTelefone\'])) :  \'\'; ?></option></select></div></td></tr></tbody></table>');
T

Com relação ao seu problema tem algo que você poderia estar fazendo que seria assim.

no javascript vc faria assim

//Aqui é um campo que será gerado no html
var telefone = '<p>  <label for="ddd">DDD: </label>   
    <input type="text" name="ddd" maxlength="2" onKeyPress="return txtBoxFormat(this, '99', event);" onChange="return txtBoxFormat(this, '9999-9999', event);" value="" />
               
  <label for="tel" class="inline">Telefone: </label>   
    <input type="text" name="tel"maxlength="9" onKeyPress="return txtBoxFormat(this, '9999-9999', event);" onChange="return txtBoxFormat(this, '9999-9999', event);" value="" />   
</p> ';

//Aqui ele encontra o último elemento do tipo input cujo name seja tel e acessa o parent dele, ou seja, superior a ele... a tag <P> e inclui após ele o elemento;
$("input[name=tel]:last").parent().after().appendTo(telefone);

//assim ele cria pra você o campo...

Com relação ao php, como você disse que iria criar no máximo 3 telefones… vc poderia simplesmente verificar no php se estão setados utilizando a função isset
assim:

$pessoa;

if (isset[$_POST['tel'])
{
   $pessoa->tel = $_POST['tel'];
}

if (isset[$_POST['cel'])
{
   $pessoa->cel = $_POST['cel'];
}

if (isset[$_POST['tel_comercial'])
{
   $pessoa->tel_comercial = $_POST['tel_comercial'];
}

Espero que apesar da demora da resposta aqui, sirva de ajuda.
Existem outras maneiras de se fazer isso, mas essa é uma bem simples que já cheguei a utilizar em algum momento.

Criado 18 de abril de 2011
Ultima resposta 28 de jun. de 2011
Respostas 11
Participantes 3