Lançado Adianti Framework 7.6!
Clique aqui para saber mais
colocar mascara cpf/cnpj conforme pessoa fisica ou juridica peguei esta função javascript só que está dando ERRO ao carregar o formulário, $script = new TElement('script'); $script->type = 'text/javascript'; $javascript = " $('select[name="pessoa"]').change(function(event){ var tipoPessoa $('select[name="pessoa"] > option:selected').each(function(){ tipoPessoa = $(this).text(); }); if(tipoPessoa == 'F') { ...
RS
colocar mascara cpf/cnpj conforme pessoa fisica ou juridica  
peguei esta função javascript só que está dando ERRO ao carregar o formulário,

$script = new TElement('script');
$script->type = 'text/javascript';
$javascript = "

$('select[name="pessoa"]').change(function(event){
var tipoPessoa
$('select[name="pessoa"] > option:selected').each(function(){
tipoPessoa = $(this).text();
});
if(tipoPessoa == 'F') {
$('input[name="cpf_cnpj"]').val('');
$('input[name="cpf_cnpj"]').attr({onkeypress:'return tentry_mask(this,event,"999.999.999-99")'});
}
if(tipoPessoa == 'J') {
$('input[name="cpf_cnpj"]').val('');
$('input[name="cpf_cnpj"]').attr({onkeypress:'return tentry_mask(this,event,"99.999.999/9999-99")'});
}
});
";
$script->add($javascript);
parent::add($script);

Curso completo Meu Negócio Pronto
Use para si, ou transforme em um negócio: Inclui aulas e códigos-fontes
Gestor de conteúdo (SITE) + Loja Virtual (E-Commerce) + Emissor de Notas para infoprodutos


Meu negócio pronto Quero me inscrever agora!

Comentários (21)


MG

Qual erro?
RS

ele da simplismente ERRO e não abre

se tem algum exemplo de como posso fazer isso?
MG


Vc comenta que simplesmente dá erro, mas não exibe nenhuma exception?
Posta o código completo.
MG


Vc comenta que simplesmente dá erro, mas não exibe nenhuma exception?
Posta o código completo.
RS


  1. <?php
  2. /**
  3.  * LocadoresForm Form
  4.  * @author  <your name here>
  5.  */
  6. class LocadoresForm extends TPage //TWindow
  7. {
  8.     protected $form// form
  9.     
  10.     /**
  11.      * Form constructor
  12.      * @param $param Request
  13.      */
  14.     public function __construct$param )
  15.     {
  16.         parent::__construct();
  17.         
  18.         // creates the form
  19.         $this->form = new TQuickForm('form_Locadores');
  20.         $this->form->class 'tform'// change CSS class
  21.         
  22.         $this->form->style 'display: table;width:100%'// change style
  23.         
  24.         // define the form title
  25.         $this->form->setFormTitle('Locadores');
  26.         
  27.         // create the form fields
  28.         $cod_credor = new TEntry('cod_credor');
  29.         $nm_credor = new TEntry('nm_credor');
  30.         $pessoa = new TRadioGroup('pessoa');
  31.         $cpf_cnpj = new TEntry('cpf_cnpj');
  32.         $dtna_credor = new TDate('dtna_credor');
  33.         $dtna_credor  ->setMask('dd/mm/yyyy'); 
  34.         
  35.         $pessoa_tipo = array();
  36.         $pessoa_tipo['F'] = 'Física';
  37.         $pessoa_tipo['J'] = 'Jurídica';
  38.         $pessoa->addItems($pessoa_tipo);
  39.         
  40.         
  41.         
  42.         // add the fields
  43.         $this->form->addQuickField('Código'$cod_credor,  100 );
  44.         $this->form->addQuickField('Nome'$nm_credor,  600 );
  45.         $this->form->addQuickField('Pessoa'$pessoa,  250 );
  46.         $this->form->addQuickField('CNPJ/CPF'$cpf_cnpj,  200 );
  47.         $this->form->addQuickField('Data Nascimento'$dtna_credor,  100 );
  48.         
  49.         
  50.        // $pessoa->setChangeAction( new TAction( array($this, 'onGenderChange' )) );
  51.        
  52.        
  53.         $script = new TElement('script'); 
  54.         $script->type 'text/javascript';
  55.         
  56.         $javascript 
  57.         
  58.         $('select[name="pessoa"]').change(function(event){ 
  59.         var tipoPessoa 
  60.         $('select[name="pessoa"] > option:selected').each(function(){ 
  61.         tipoPessoa = $(this).text(); 
  62.         }); 
  63.         
  64.         if(tipoPessoa == 'F') { 
  65.            $('input[name="cpf_cnpj"]').val(''); 
  66.            $('input[name="cpf_cnpj"]').attr({onkeypress:'return tentry_mask(this,event,"999.999.999-99")'}); 
  67.         } 
  68.         
  69.         if(tipoPessoa == 'J') { 
  70.             $('input[name="cpf_cnpj"]').val(''); 
  71.             $('input[name="cpf_cnpj"]').attr({onkeypress:'return tentry_mask(this,event,"99.999.999/9999-99")'}); 
  72.         }
  73.          
  74.         })";
  75.         
  76.         $script->add($javascript); 
  77.         parent::add($script); 
  78.        
  79.         if (!empty($cod_credor))
  80.         {
  81.             $cod_credor->setEditable(FALSE);
  82.         }
  83.         
  84.         /** samples
  85.          $this->form->addQuickFields('Date', array($date1, new TLabel('to'), $date2)); // side by side fields
  86.          $fieldX->addValidation( 'Field X', new TRequiredValidator ); // add validation
  87.          $fieldX->setSize( 100, 40 ); // set size
  88.          **/
  89.          
  90.         // create the form actions
  91.         $this->form->addQuickAction(_t('Save'), new TAction(array($this'onSave')), 'fa:floppy-o');
  92.      //   $this->form->addQuickAction(_t('New'),  new TAction(array($this, 'onClear')), 'bs:plus-sign green');
  93.          $this->form->addQuickAction('Voltar',  new TAction(array('LocadoresList''onReload')), 'fa:undo blue');
  94.        
  95.         // vertical box container
  96.         $container = new TVBox;
  97.         $container->style 'width: 90%';
  98.         // $container->add(new TXMLBreadCrumb('menu.xml', __CLASS__));
  99.         $container->add($this->form);
  100.         
  101.         parent::add($container);
  102.     }
  103.     /**
  104.      * Save form data
  105.      * @param $param Request
  106.      */
  107.      
  108.    public static function onGenderChange($param)
  109.     {
  110.                 
  111.         if ($param['pessoa']='F')
  112.         {
  113.            
  114.             $cpf_cnpj->setMask('999.999.999-99'); 
  115.             TEntry::reload('form_Locadores');
  116.         }
  117.         
  118.        
  119.     }
  120.     public function onSave$param )
  121.     {
  122.         try
  123.         {
  124.             TTransaction::open('db_contratos'); // open a transaction
  125.             
  126.           
  127.             $this->form->validate(); // validate form data
  128.             
  129.              $object $this->form->getData('Locadores');
  130.             
  131.             $object->dtna_credorTDate::date2us($object->dtna_credor);
  132.             
  133.             $object->store(); // save the object
  134.             
  135.             $this->form->setData($object); // fill form data
  136.             TTransaction::close(); // close the transaction
  137.             
  138.             new TMessage('info'TAdiantiCoreTranslator::translate('Record saved'));
  139.         }
  140.         catch (Exception $e// in case of exception
  141.         {
  142.             new TMessage('error'$e->getMessage()); // shows the exception error message
  143.             $this->form->setData$this->form->getData() ); // keep form data
  144.             TTransaction::rollback(); // undo all pending operations
  145.         }
  146.     }
  147.     
  148.     /**
  149.      * Clear form data
  150.      * @param $param Request
  151.      */
  152.     public function onClear$param )
  153.     {
  154.         $this->form->clear(TRUE);
  155.     }
  156.     
  157.     /**
  158.      * Load object to form data
  159.      * @param $param Request
  160.      */
  161.     public function onEdit$param )
  162.     {
  163.         try
  164.         
  165.         {
  166.             if (isset($param['key']))
  167.             {
  168.                 $key $param['key'];  // get the parameter $key
  169.                 TTransaction::open('db_contratos'); // open a transaction
  170.                 $object = new Locadores($key); // instantiates the Active Record
  171.                 $object->dtna_credor TDate::date2br($object->dtna_credor);
  172.                 $this->form->setData($object); // fill the form
  173.                 TTransaction::close(); // close the transaction
  174.                 
  175.             }
  176.             else
  177.             {
  178.                 $this->form->clear(TRUE);
  179.             }
  180.         }
  181.         catch (Exception $e// in case of exception
  182.         {
  183.             new TMessage('error'$e->getMessage()); // shows the exception error message
  184.             TTransaction::rollback(); // undo all pending operations
  185.         }
  186.     }
  187. }
  188. ?>
</your>
MG

Tenta usar essa :

  1. <?php
  2.         //******************************************************************
  3.         //script para definir a mascara do cpf/cn
  4.         $script = new TElement('script'); 
  5.         $script->type 'text/javascript';
  6.         $javascript 
  7.             $(document).on('change','select[name=\"tipo_pessoa_id\"]' , function(event){
  8.                 //alert('Entrou');
  9.                 $('input[name=\"cpf_cnpj\"]').val('');
  10.                
  11.                 $('select[name=\"tipo_pessoa_id\"] > option:selected').each(function(){
  12.                     tipoPessoa = $(this).text();
  13.                 });
  14.                 if(tipoPessoa.toLowerCase() == 'física') {
  15.                     $('input[name=\"cpf_cnpj\"]').val('');
  16.                     $('input[name=\"cpf_cnpj\"]').attr({onkeypress:'return tentry_mask(this,event,\"999.999.999-99\")'});                        
  17.                  }
  18.                  if(tipoPessoa.toLowerCase() == 'jurídica') {
  19.                      $('input[name=\"cpf_cnpj\"]').val('');
  20.                      $('input[name=\"cpf_cnpj\"]').attr({onkeypress:'return tentry_mask(this,event,\"99.999.999/9999-99\")'});                    
  21.                   }
  22.             });";
  23.         $script->add($javascript); 
  24.         $tableScriptPessoa = new TTable;
  25.         $tableScriptPessoa->addRow()->addCell($script);
  26.         //*****************************************************************
  27.         $container->add($tableScriptPessoa);
  28. ?>
MG

Estou reenviando em texto puro, pois o "escape" não foi corretamente exibido.

$script = new TElement('script');
$script->type = 'text/javascript';
$javascript = "
$(document).on('change','select[name="tipo_pessoa_id"]' , function(event){
//alert('Entrou');
$('input[name="cpf_cnpj"]').val('');

$('select[name="tipo_pessoa_id"] > option:selected').each(function(){
tipoPessoa = $(this).text();
});
if(tipoPessoa.toLowerCase() == 'física') {
$('input[name="cpf_cnpj"]').val('');
$('input[name="cpf_cnpj"]').attr({onkeypress:'return tentry_mask(this,event,"999.999.999-99")'});
}
if(tipoPessoa.toLowerCase() == 'jurídica') {
$('input[name="cpf_cnpj"]').val('');
$('input[name="cpf_cnpj"]').attr({onkeypress:'return tentry_mask(this,event,"99.999.999/9999-99")'});
}

});";
MG

Bom, novamente o escape não funcionou.
Mas em 'select[name=\"tipo_pessoa_id\"]'
Antes das aspas duplas deve ser "escapado" com barra invertida.
Eu uso este código e funciona muito bem.
CS

O meu ta assim com seus mesmos dados, apenas com $pessoa = new TCombo('pessoa');
$javascript = "

$('select[name="pessoa"]').change(function(event){
var tipoPessoa
$('select[name="pessoa"] > option:selected').each(function(){
tipoPessoa = $(this).text();
});
if(tipoPessoa == 'Física') {
$('input[name="cpf_cnpj"]').val('');
$('input[name="cpf_cnpj"]').attr({onkeypress:'return tentry_mask(this,event,"999.999.999-99")'});
}
if(tipoPessoa == 'Jurídica') {
$('input[name="cpf_cnpj"]').val('');
$('input[name="cpf_cnpj"]').attr({onkeypress:'return tentry_mask(this,event,"99.999.999/9999-99")'});
}
});

";
CS

Lógico que com os caracteres de escape...
CS

Testando com o code:
$javascript = " $('select[name=\"pessoa\"]').change(function(event){ var tipoPessoa $('select[name=\"pessoa\"] > option:selected').each(function(){ tipoPessoa = $(this).text(); }); if(tipoPessoa == 'Física') { $('input[name=\"cpf_cnpj\"]').val(''); $('input[name=\"cpf_cnpj\"]').attr({onkeypress:'return tentry_mask(this,event,\"999.999.999-99\")'}); } if(tipoPessoa == 'Jurídica') { $('input[name=\"cpf_cnpj\"]').val(''); $('input[name=\"cpf_cnpj\"]').attr({onkeypress:'return tentry_mask(this,event,\"99.999.999/9999-99\")'}); } }); ";
CS

Também corta os caracteres de escape...
MG

Nenhum exception é exibida?
Comigo funciona.
Estou num curso agora assim que possível posto meu código.
RS

  1. <?php
  2. $script = new TElement('script'); 
  3.         $script->type 'text/javascript';
  4.         $javascript 
  5.         $('select[name=\"pessoa\"]').change(function(event){ 
  6.         var tipoPessoa 
  7.         $('select[name=\"pessoa\"] > option:selected').each(function(){ 
  8.         tipoPessoa = $(this).text(); 
  9.         }); 
  10.         if(tipoPessoa == 'F') { 
  11.         $('input[name="cpf_cnpj"]').val(''); 
  12.         $('input[name="cpf_cnpj"]').attr({onkeypress:'return tentry_mask(this,event,"999.999.999-99")'}); 
  13.         } 
  14.         if(tipoPessoa == 'J') { 
  15.         $('input[name="cpf_cnpj"]').val(''); 
  16.         $('input[name="cpf_cnpj"]').attr({onkeypress:'return tentry_mask(this,event,"99.999.999/9999-99")'}); 
  17.         } 
  18.         }); 
  19.         
  20.         ";
  21.         $script->add($javascript);  
  22. ?>


ai deu: Parse error: syntax error, unexpected 'cpf_cnpj' (T_STRING) in C:wampwwwadm_contratosappcontrolLocadoresForm.class.php on line 62
RS

$('select[name="pessoa"]').change(function(event){
var tipoPessoa
$('select[name="pessoa"] > option:selected').each(function(){
tipoPessoa = $(this).text();
});
if(tipoPessoa == 'F') {
$('input[name="cpf_cnpj"]').val('');
$('input[name="cpf_cnpj"]').attr({onkeypress:'return tentry_mask(this,event,"999.999.999-99")'});
}
if(tipoPessoa == 'J') {
$('input[name="cpf_cnpj"]').val('');
$('input[name="cpf_cnpj"]').attr({onkeypress:'return tentry_mask(this,event,"99.999.999/9999-99")'});
}
});

";
$script->add($javascript);
MG

Posta a linha 62 do erro.
Pois no código original que postou não deu pra identificar.
A linha 62 faz referência ao script.
RS

quando você falam que tenho que colocar escape é onde?

é nestas duas linhas?


$('select[name="pessoa"]').change(function(event){
var tipoPessoa
$('select[name="pessoa"] > option:selected').each(function(){
tipoPessoa = $(this).text();
});


o erro esta dando na linha

$('input[name="cpf_cnpj"]').val('');
$('input[name="cpf_cnpj"]').attr({onkeypress:'return tentry_mask(this,event,"999.999.999-99")'});
}
MG

Sim, você deve colocar a barra invertida antes das aspas duplas quanto está dentro de outra aspas.
Por exemplo [name="cpf_cnpj"] o mesmo para pesssoa.
MG

Novamente o navegador interpretou o escape.
Vou tentar o code.
[name=\"pessoa\"]
RS

pessoal obrigado pela ajuda, o problema era que eu pesava que o tipopessoa = $(this).text() pegasse o ['F'] ou ['J'] mas ele pega o Físico e Jurídico e estava testando se fosse igual a 'F' ou 'J' e tem que ser 'Jurídica' ou 'Física'.

Muito obrigado.
RS

agora gostaria de validar, se o CPF ou CNPJ é válido, vi que poderia usar o $cpf_cnpj->addValidation('cpf_cnpj', new TCPFValidator) mas o problema que tenho que fazer conforme o tipopessoa.