IU
Javascript para alteração de máscara de I.E.
Olá,
Sou novo com javascript, procurei aqui mesmo no fórum sobre o assunto para a implementação de código dentro de um formulário, mas não consegui nenhum resultado que explique com mais detalhes sobre o assunto.
Normalmente tem somente o trecho de código referente a tal função. Por isso venho por meio deste tirar algumas dúvidas de como escrever o código e onde escrever.
Primeiro, segue abaixo um formulário de cadastro de cliente, onde estou tendo dificuldade de alterar a máscara do campo I.E. conforme o Estado em que a pessoa se encontra:
Porém não funciona ao executar a página, na verdade ele gera um erro de sintaxe na linha
$script = new TElement('script');
Como eu faço pra funcionar isso ?
Sou novo com javascript, procurei aqui mesmo no fórum sobre o assunto para a implementação de código dentro de um formulário, mas não consegui nenhum resultado que explique com mais detalhes sobre o assunto.
Normalmente tem somente o trecho de código referente a tal função. Por isso venho por meio deste tirar algumas dúvidas de como escrever o código e onde escrever.
Primeiro, segue abaixo um formulário de cadastro de cliente, onde estou tendo dificuldade de alterar a máscara do campo I.E. conforme o Estado em que a pessoa se encontra:
- <?php
- class ClienteForm extends TPage
- {
- protected $form; // form
-
- public function __construct( $param )
- {
- parent::__construct();
-
- try
- {
- TTransaction::open('itisu420_sistema2');
-
- // CRIAÇÃO DO FORMULÁRIO
- $this->form = new TForm('form_Cliente');
-
- $page = new TTable;
- //$page->border = '1';
- $this->form->add($page);
-
- // CRIAÇÃO DOS CAMPOS DO FORMULÁRIO
- $id = new TEntry('id');
- $dt_abertura = new TDate('dt_abertura');
- $nome_fantasia = new TEntry('nome_fantasia');
- $razao_social = new TEntry('razao_social');
- $cnpj = new TEntry('cnpj');
- $cpf = new TEntry('cpf');
-
- $estado = new TCombo('estado');
- $uf = array('AC'=>'ACRE', 'AL'=>'ALAGOAS', 'AP'=>'AMAPÁ', 'AM'=>'AMAZONAS', 'BA'=>'BAHIA', 'CE'=>'CEARÁ', 'DF'=>'DISTRITO FEDERAL', 'ES'=>'ESPÍRITO SANTO',
- 'GO'=>'GOIÁS', 'MA'=>'MARANHÃO', 'MT'=>'MATO GROSSO', 'MS'=>'MATO GROSSO DO SUL', 'MG'=>'MINAS GERAIS', 'PA'=>'PARÁ', 'PB'=>'PARAÍBA', 'PR'=>'PARANÁ',
- 'PE'=>'PERNAMBUCO', 'PI'=>'PIAUÍ', 'RJ'=>'RIO DE JANEIRO', 'RN'=>'RIO GRNADE DO NORTE', 'RS'=>'RIO GRANDE DO SUL', 'RO'=>'RONDÔNIA', 'RR'=>'RORAIMA',
- 'SC'=>'SANTA CATARINA', 'SP'=>'SÃO PAULO', 'SE'=>'SERGIPE', 'TO'=>'TOCANTINS');
- $estado->addItems($uf);
- $ie = new TEntry('ie');
- $ra = new TEntry('ra');
- $margem = new TEntry('margem');
- $cep = new TEntry('cep');
- $endereco = new TEntry('endereco');
- $numero = new TEntry('numero');
- $complemento = new TEntry('complemento');
- $bairro = new TEntry('bairro');
- $cidade = new TEntry('cidade');
- $telf = new TEntry('telf');
- $telm = new TEntry('telm');
- $email = new TEntry('email');
- $siteweb = new TEntry('siteweb');
-
- $estrangeiro = new TRadioGroup('estrangeiro');
- $opcoes_estrangeiro = array('s' => 'SIM', 'n' => 'NÃO');
- $estrangeiro->addItems($opcoes_estrangeiro);
- $estrangeiro->setLayout('horizontal');
-
- $suframa = new TEntry('suframa');
-
- // HABILITA/DESABILITA CAMPOS PARA EDIÇÃO
- $id->setEditable(FALSE);
-
- // MÁSCARAS
- $dt_abertura->setMask('dd/mm/yyyy');
- $cnpj->setMask('99.999.999/9999-99');
- $cpf->setMask('999.999.999-99');
- $telf->setMask('(99)9999-9999');
- $telm->setMask('(99)99999-9999');
- $suframa->setMask('999999999');
- $nome_fantasia->setMaxLength(60);
- $razao_social->setMaxLength(100);
- $email->setMaxLength(50);
- $siteweb->setMaxLength(60);
- $cep->setMask('99999-999');
- $numero->setMaxLength(10);
- $complemento->setMaxLength(30);
- $endereco->setMaxLength(60);
- $cidade->setMaxLength(40);
- $ra->setMaxLength(10);
- $margem->setMaxLength(10);
- $bairro->setMaxLength(20);
- $ie->setMaxLength(17);
-
- // TÍTULO DA TABELA
- $title1 = new TLabel('CADASTRO DE CLIENTES');
- $title1->setFontColor('#3b8b8b');
- $title1->setFontSize('18');
-
- $row = $page->addRow();
- $title1 = $row->addCell($title1);
- $title1->colspan = 6;
-
- // ADIÇÃO DOS CAMPOS ID E DATA DE ABERTURA NA TABELA PRINCIPAL (PAGE)
- $row = $page->addRow();
- $cell = $row->addCell(new TLabel('ID'));
- $cell->colspan = 3;
- $cell = $row->addCell(new TLabel('DATA ABERTURA'));
- $cell->colspan = 3;
- $row = $page->addRow();
- $cell = $row->addCell($id);
- $cell->colspan = 3;
- $cell = $row->addCell($dt_abertura);
- $cell->colspan = 3;
-
- // FRAME 1
- $frame1 = new TFrame;
- $frame1->setLegend('Dados do Cliente');
- $frame1->oid = 'frame1-dados';
- $botao1 = new TButton('show hide');
- $botao1->class = 'btn btn-info';
- $botao1->setLabel('M/O - Dados');
- $botao1->addFunction("\$('[oid=frame1-dados]').slideToggle(); $(this).toggleClass( 'active' )");
-
- // ADIÇÃO DOS BOTÕES MOSTRAR/OCULTAR
- $row = $page->addRow();
- $botao1 = $row->addCell($botao1);
- $botao1->colspan = 6;
-
- // ADIÇÃO DO FRAME 1
- $row = $page->addRow();
- $cell = $row->addCell($frame1);
- $cell->colspan = 6;
-
- $page1 = new TTable;
- $frame1->add($page1);
-
- $row = $page1->addRow();
- $cell = $row->addCell(new TLabel('Nome Fantasia'));
- $cell->colspan = 6;
- $row = $page1->addRow();
- $cell = $row->addCell($nome_fantasia);
- $cell->colspan = 6;
-
- $row = $page1->addRow();
- $cell = $row->addCell(new TLabel('Razão Social'));
- $cell->colspan = 6;
- $row = $page1->addRow();
- $cell = $row->addCell($razao_social);
- $cell->colspan = 6;
-
- $row = $page1->addRow();
- $cell = $row->addCell(new TLabel('CNPJ'));
- $cell->colspan = 2;
- $cell = $row->addCell(new TLabel('CPF'));
- $cell->colspan = 2;
- $cell = $row->addCell(new TLabel('ESTRANGEIRO'));
- $cell->colspan = 2;
- $row = $page1->addRow();
- $cell = $row->addCell($cnpj);
- $cell->colspan = 2;
- $cell = $row->addCell($cpf);
- $cell->colspan = 2;
- $cell = $row->addCell($estrangeiro);
- $cell->colspan = 2;
-
- $row = $page1->addRow();
- $row->addCell(new TLabel('Estado'));
- $row->addCell(new TLabel('I.E.'));
- $row->addCell(new TLabel('RA'));
- $row->addCell(new TLabel('Margem'));
- $row = $page1->addRow();
- $row->addCell($estado);
- $row->addCell($ie);
- $row->addCell($ra);
- $row->addCell($margem);
-
- // ADIÇÃO DOS BOTÕES MOSTRAR/OCULTAR
- $frame2 = new TFrame;
- $frame2->setLegend('Endereço do Cliente');
- $frame2->oid = 'frame2-endereco';
- $botao2 = new TButton('show hide');
- $botao2->class = 'btn btn-info';
- $botao2->setLabel('M/O - Endereço');
- $botao2->addFunction("\$('[oid=frame2-endereco]').slideToggle(); $(this).toggleClass( 'active' )");
-
- // ADIÇÃO DOS BOTÕES MOSTRAR/OCULTAR
- $row = $page->addRow();
- $botao2 = $row->addCell($botao2);
- $botao2->colspan = 6;
-
- // ADIÇÃO DO FRAME 2
- $row = $page->addRow();
- $cell = $row->addCell($frame2);
- $cell->colspan = 6;
-
- $page2 = new TTable;
- $frame2->add($page2);
-
- $row = $page2->addRow();
- $cell = $row->addCell(new TLabel('CEP'));
- $cell->colspan = 2;
- $cell = $row->addCell(new TLabel('Endereço'));
- $cell->colspan = 2;
- $cell = $row->addCell(new TLabel('Número'));
- $cell->colspan = 2;
- $row = $page2->addRow();
- $cell = $row->addCell($cep);
- $cell->colspan = 2;
- $cell = $row->addCell($endereco);
- $cell->colspan = 2;
- $cell = $row->addCell($numero);
- $cell->colspan = 2;
-
- $row = $page2->addRow();
- $cell = $row->addCell(new TLabel('Complemento'));
- $cell->colspan = 2;
- $cell = $row->addCell(new TLabel('Bairro'));
- $cell->colspan = 2;
- $cell = $row->addCell(new TLabel('Cidade'));
- $cell->colspan = 2;
- $row = $page2->addRow();
- $cell = $row->addCell($complemento);
- $cell->colspan = 2;
- $cell = $row->addCell($bairro);
- $cell->colspan = 2;
- $cell = $row->addCell($cidade);
- $cell->colspan = 2;
-
- $row = $page2->addRow();
- $cell = $row->addCell(new TLabel('Tel.Fixo'));
- $cell->colspan = 2;
- $cell = $row->addCell(new TLabel('Tel.Móvel'));
- $cell->colspan = 2;
- $cell = $row->addCell(new TLabel('Email'));
- $cell->colspan = 2;
- $row = $page2->addRow();
- $cell = $row->addCell($telf);
- $cell->colspan = 2;
- $cell = $row->addCell($telm);
- $cell->colspan = 2;
- $cell = $row->addCell($email);
- $cell->colspan = 2;
-
- $row = $page2->addRow();
- $cell = $row->addCell(new TLabel('Website'));
- $cell->colspan = 6;
- $row = $page2->addRow();
- $cell = $row->addCell($siteweb);
- $cell->colspan = 6;
-
- $row = $page2->addRow();
- $cell = $row->addCell(new TLabel('SUFRAMA'));
- $cell->colspan = 6;
- $row = $page2->addRow();
- $cell = $row->addCell($suframa);
- $cell->colspan = 2;
-
- // CRIACAO DOS BOTÕES
-
- $botao4 = new TButton('save');
- $botao4->setAction( new TAction(array($this,'onSave')), _t('Save'));
- $botao4->setImage('fa:floppy-o');
- $row = $page->addRow();
- $cell = $row->addCell($botao4);
- $cell->colspan = 1;
-
- $botao5 = new TButton('new');
- $botao5->setAction( new TAction(array($this, 'onClear')), _t('New'));
- $botao5->setImage('bs:plus-sign green');
- $cell = $row->addCell($botao5);
- $cell->colspan = 1;
-
- $botao6 = new TButton('Voltar');
- $botao6->setAction( new TAction(array('ClienteList', 'onReload')), 'Voltar');
- $botao6->setImage('fa:mail-reply blue');
- $cell = $row->addCell($botao6);
- $cell->colspan = 1;
-
- //---------------------------------------------------------------------------------------
- // ------------- FIM FORMULARIO --------------
- //---------------------------------------------------------------------------------------
- $this->form->setFields( array($id, $dt_abertura, $nome_fantasia, $razao_social, $cnpj, $cpf, $estado, $ie, $ra, $margem, $cep, $endereco,
- $numero, $complemento, $bairro, $cidade, $telf, $telm, $email, $siteweb, $estrangeiro, $suframa,
- $botao4, $botao5, $botao6));
-
- $script = new TElement('script');
- $script->type = 'text/javascript';
- $javascript = "
- // personaliza os campos de acordo com o ESTADO
- $( 'select[name="estado"]' ).change( function( event ){ var tipoEstado $( 'select[name="estado"] > option:selected' ).each( function(){ tipoEstado = $(this).text(); });
- if(tipoEstado == 'AC') { $('input[name="ie"]').val(''); $('input[name="ie"]').attr( {onkeypress:'return tentry_mask(this,event,"99.999.999/999-99")'} ); }
- if(tipoEstado == 'AL') { $('input[name="ie"]').val(''); $('input[name="ie"]').attr( {onkeypress:'return tentry_mask(this,event,"999999999")'} ); }
- if(tipoEstado == 'AP') { $('input[name="ie"]').val(''); $('input[name="ie"]').attr( {onkeypress:'return tentry_mask(this,event,"9999999999")'} ); }
- if(tipoEstado == 'AM') { $('input[name="ie"]').val(''); $('input[name="ie"]').attr( {onkeypress:'return tentry_mask(this,event,"99.999.999-9")'} ); }
- if(tipoEstado == 'BH') { $('input[name="ie"]').val(''); $('input[name="ie"]').attr( {onkeypress:'return tentry_mask(this,event,"999999-99")'} ); }
- if(tipoEstado == 'CE') { $('input[name="ie"]').val(''); $('input[name="ie"]').attr( {onkeypress:'return tentry_mask(this,event,"99999999-9")'} ); }
- if(tipoEstado == 'DF') { $('input[name="ie"]').val(''); $('input[name="ie"]').attr( {onkeypress:'return tentry_mask(this,event,"99999999999-99")'} ); }
- if(tipoEstado == 'ES') { $('input[name="ie"]').val(''); $('input[name="ie"]').attr( {onkeypress:'return tentry_mask(this,event,"99999999-9")'} ); }
- if(tipoEstado == 'GO') { $('input[name="ie"]').val(''); $('input[name="ie"]').attr( {onkeypress:'return tentry_mask(this,event,"99.999.999-9")'} ); }
- if(tipoEstado == 'MA') { $('input[name="ie"]').val(''); $('input[name="ie"]').attr( {onkeypress:'return tentry_mask(this,event,"99999999-9")'} ); }
- if(tipoEstado == 'MT') { $('input[name="ie"]').val(''); $('input[name="ie"]').attr( {onkeypress:'return tentry_mask(this,event,"9999999999-9")'} ); }
- if(tipoEstado == 'MS') { $('input[name="ie"]').val(''); $('input[name="ie"]').attr( {onkeypress:'return tentry_mask(this,event,"99999999-9")'} ); }
- if(tipoEstado == 'MG') { $('input[name="ie"]').val(''); $('input[name="ie"]').attr( {onkeypress:'return tentry_mask(this,event,"999.999.999/9999")'} ); }
- if(tipoEstado == 'PA') { $('input[name="ie"]').val(''); $('input[name="ie"]').attr( {onkeypress:'return tentry_mask(this,event,"99-999999-9")'} ); }
- if(tipoEstado == 'PB') { $('input[name="ie"]').val(''); $('input[name="ie"]').attr( {onkeypress:'return tentry_mask(this,event,"99999999-9")'} ); }
- if(tipoEstado == 'PR') { $('input[name="ie"]').val(''); $('input[name="ie"]').attr( {onkeypress:'return tentry_mask(this,event,"999.99999-99")'} ); }
- if(tipoEstado == 'PE') { $('input[name="ie"]').val(''); $('input[name="ie"]').attr( {onkeypress:'return tentry_mask(this,event,"9999999-99")'} ); }
- if(tipoEstado == 'PI') { $('input[name="ie"]').val(''); $('input[name="ie"]').attr( {onkeypress:'return tentry_mask(this,event,"99999999-9")'} ); }
- if(tipoEstado == 'RJ') { $('input[name="ie"]').val(''); $('input[name="ie"]').attr( {onkeypress:'return tentry_mask(this,event,"99.999.99-9")'} ); }
- if(tipoEstado == 'RN') { $('input[name="ie"]').val(''); $('input[name="ie"]').attr( {onkeypress:'return tentry_mask(this,event,"99.999.999-9")'} ); }
- if(tipoEstado == 'RS') { $('input[name="ie"]').val(''); $('input[name="ie"]').attr( {onkeypress:'return tentry_mask(this,event,"999/9999999")'}); }
- if(tipoEstado == 'RO') { $('input[name="ie"]').val(''); $('input[name="ie"]').attr( {onkeypress:'return tentry_mask(this,event,"9999999999999-9")'} ); }
- if(tipoEstado == 'RR') { $('input[name="ie"]').val(''); $('input[name="ie"]').attr( {onkeypress:'return tentry_mask(this,event,"99999999-9")'} ); }
- if(tipoEstado == 'SC') { $('input[name="ie"]').val(''); $('input[name="ie"]').attr( {onkeypress:'return tentry_mask(this,event,"999.999.999")'} ); }
- if(tipoEstado == 'SP') { $('input[name="ie"]').val(''); $('input[name="ie"]').attr( {onkeypress:'return tentry_mask(this,event,"999.999.999.999")'} ); }
- if(tipoEstado == 'SE') { $('input[name="ie"]').val(''); $('input[name="ie"]').attr( {onkeypress:'return tentry_mask(this,event,"99999999-9")'} ); }
- if(tipoEstado == 'TO') { $('input[name="ie"]').val(''); $('input[name="ie"]').attr( {onkeypress:'return tentry_mask(this,event,"9999999999-9")'} ); }
- ";
- $script->add($javascript);
- parent::add($script);
-
-
- if (!empty($id))
- {
- $id->setEditable(FALSE);
- }
- // vertical box container
- $conteiner = new TVBox;
- $conteiner->style = 'width: 100%';
- $conteiner->add($this->form);
-
- TTransaction::close();
- }
- catch (Exception $e)
- {
- new TMessage('error', $e->getMessage());
- }
- parent::add($conteiner);
-
- }
-
- public function onSave( $param )
- {
- try
- {
- TTransaction::open('itisu420_sistema2'); // open a transaction
-
- $this->form->validate(); // validate form data
-
- $object = new Cliente; // create an empty object
- $data = $this->form->getData(); // get form data as array
- $object->fromArray( (array) $data); // load the object with data
- $object->dt_abertura = TDate::date2us($object->dt_abertura);
- $object->store(); // save the object
-
- // get the generated id
- $data->id = $object->id;
-
- $object->dt_abertura = TDate::date2br($object->dt_abertura);
-
- $this->form->setData($data); // fill form data
- TTransaction::close(); // close the transaction
-
- new TMessage('info', TAdiantiCoreTranslator::translate('Record saved'));
- }
- catch (Exception $e) // in case of exception
- {
- new TMessage('error', $e->getMessage()); // shows the exception error message
- $this->form->setData( $this->form->getData() ); // keep form data
- TTransaction::rollback(); // undo all pending operations
- }
- }
-
- public function onClear( $param )
- {
- $this->form->clear();
- }
-
- public function onEdit( $param )
- {
- try
- {
- if (isset($param['key']))
- {
- $key = $param['key']; // get the parameter $key
- TTransaction::open('itisu420_sistema2'); // open a transaction
- $object = new Cliente($key); // instantiates the Active Record
- $object->dt_abertura = TDate::date2br($object->dt_abertura);
- $this->form->setData($object); // fill the form
- TTransaction::close(); // close the transaction
- }
- else
- {
- $this->form->clear();
- }
- }
- catch (Exception $e) // in case of exception
- {
- new TMessage('error', $e->getMessage()); // shows the exception error message
- TTransaction::rollback(); // undo all pending operations
- }
- }
-
- public function formatDate($date, $object)
- {
- $dt = new DateTime($date);
- return $dt->format('d/m/y');
- }
-
- }
- ?>
Porém não funciona ao executar a página, na verdade ele gera um erro de sintaxe na linha
$script = new TElement('script');
Como eu faço pra funcionar isso ?
Está dando erro por causa das aspas duplas. Por exemplo, no começo da string você abriu aspas duplas e depois do 'name=' adicionou novamente as aspas:
Outra coisa que percebi, se sua intenção é buscar o valor selecionado na combo, pode fazer o seguinte:
E em cada if dos estados precisa ajustar:
Ao postar sumiram as barras. Seria:
tentry_mask(this,event,contra-barra + aspa simples + mascara + contra-barra + aspa_simples)
Ok, entendido e corrigido, porém ele ainda gera um erro na linha 274: $script->type = 'text/javascript';
-> "Parse error: parse error in C:wamp64wwwitisu420sistema2appcontrolClienteClienteForm.class.php on line 274
Errors parsing C:wamp64wwwitisu420sistema2appcontrolClient".
Se eu retiro esta linha ele gera outro erro: $javascript = "
-> "Parse error: parse error in C:wamp64wwwitisu420sistema2appcontrolClienteClienteForm.class.php on line 275
Errors parsing C:wamp64wwwitisu420sistema2appcontrolClienteClienteForm.class.php"
Como eu corrigo isto ?
Na linha 274 eu reescrevi o código:
e não deu mais o erro.
Porém ainda continua o erro na linha 275.
Na linha 274 eu reescrevi o código:
e não deu mais o erro.
Porém ainda continua o erro na linha 275.
Estou com um problema parecido mas no meu caso não dá erro mas também não executa o scrip
Igor, pela mensagem de erro parece ainda ser problema com as aspas.
Leildon, acho que faltou fechar um parêntese após o fechamento da última chave. E veja também minha resposta anterior sobre as contra-barras dentro de tentry_mask
Acrescente ");"
Na dúvida postem os códigos no pastebin
Nataniel, eu já tirei as aspas duplas, mas nada ainda.
Eu preciso declarar esta variável em algum lugar antes de escrever o código ?
EU preciso escrever este código em algum arquivo separado, tipo .js e colocar um #include em no cabeçalho do classe ou no formulário ?
Existe algo que é necessário fazer antes ou somente declarar a variável como está no código-fonte já era pra ter funcionado ?
Estou meio sem saída aqui.
Tentei várias formas:
Assim também não funcionou!
Assim também não funcionou!
Será que a versão do Adianti Studio 4.0 está com algum bug ?
Ambos os códigos são strings, por isso precisam de aspas simples ou duplas no ínicio e no fim. Quando comentei que era pra tirar as aspas duplas estava me referindo as outras, presentes no meio da string.
OK, alterado.
Ficou assim todo o código:
Parse error: parse error in C:wamp64wwwitisu420sistema2appcontrolClienteClienteForm.class.php on line 40
Errors parsing C:wamp64wwwitisu420sistema2appcontrolClienteClienteForm.class.php
Neste caso a linha 40 que ele se refere é essa:
Acredite, não mudou nada, tentei todas as formas, infelizmente.
Executei o código que passou e funcionou. Às vezes pode ser cache do WAMP. Veja se consegue desabilitar o cache ou crie um novo arquivo para testar.
Fatal error: Uncaught Error: Call to undefined function new TElement() in C:wamp64wwwitisu420sistema2appcontrolClienteClienteForm.class.php
( ! ) Error: Call to undefined function new TElement() in C:wamp64wwwitisu420sistema2appcontrolClienteClienteForm.class.php
Quando executei a página na web deu o erro acima. :/
Limpei o cache e refiz novamente o código e desta vez não gerou erro de sintaxe. Porém ao executar o serviço na web ele gerou o erro:
"
Fatal error: Uncaught Error: Call to undefined function new TElement() in C:wamp64wwwitisu420sistema2appcontrolClienteClienteForm.class.php
( ! ) Error: Call to undefined function new TElement() in C:wamp64wwwitisu420sistema2appcontrolClienteClienteForm.class.php
"
Agora refiz os códigos novamente e este erro sumiu, porém apareceu a pagina carregando (loop infinito) com o seguinte Aviso:
"Warning: create default object from empty value in C:...ClienteForm.php on line....
Mas neste caso estou vendo que seria o código de referência...porém como devo resolver isso. Criar um valor padrão para o campo ?
Se for como faço isso ?
Agora refiz os códigos novamente e este erro sumiu, porém apareceu a pagina carregando (loop infinito) com o seguinte Aviso:
"Warning: create default object from empty value in C:...ClienteForm.php on line....
Mas neste caso estou vendo que seria o código de referência...porém como devo resolver isso. Criar um valor padrão para o campo ?
Se for como faço isso ?