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 Dominando o Adianti Framework

O material mais completo de treinamento do Framework.
Curso em vídeo aulas + Livro completo + Códigos fontes do projeto ERPHouse.
Conteúdo Atualizado!


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


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.