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

Mudar Evento De Um Text No Onchange No Select


Guest saga_fuel

Pergunta

Guest saga_fuel

Galera eu prescisava mudar um determinado alert que eu tenho no onkeypress da minha text quando ocorrer o onchange do meu <select>

será que alguém sabe como faz?

Link para o comentário
Compartilhar em outros sites

7 respostass a esta questão

Posts Recomendados

  • 0
Guest saga_fuel

quando mudar o onchange do meu <select> para A eu quero que o evento da minha text fique

onKeyPress ="return txtBoxFormat(this.form, this.name, '99.999.999/9999-99', event);"

QUANDO mudar o <select> para B mudar para

onKeyPress ="return txtBoxFormat(this.form, this.name, '999.999.999-99', event);"

Ou seja quero mudar a mascara do meu text conforme o o option selecionado no meu select

sera que da pra fazer isso em java script?

Link para o comentário
Compartilhar em outros sites

  • 0

Dá sim, eu tava fazendo pra mim, terminei agora, vê se serve pra você.

Ele valida e formata CPF e CNPJ. Só achei um pouco grande.... :lol:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Untitled Document</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<style type="text/css">
body,td,th {
    font-size: 12px;
}
.valido {
}
.invalido {
}
.esconde {
display:none;
}
.exibe { }
-->
</style>
<script>

    function alteraMascara() {
    
        obj = document.Form.opcao.value;
        campo = document.Form.dados;

        
        if (obj == "fisica") {

            document.getElementById("divcpf").className= "exibe";
            document.getElementById("divcnpj").className= "esconde";
            }
                if (obj == "juridica") {
                
                    document.getElementById("divcnpj").className= "exibe";
                    document.getElementById("divcpf").className= "esconde";
        }
                        
}

oldObj   = "";
oldValor = "";
inteiro  = new RegExp("[0-9]");

function checaCPF(obj)
{
  valor = obj.value;
  if(valor != oldValor || oldObj != obj){
    for(i=0;i<valor.length;i++){
      if(!inteiro.test(valor.charAt(i))){
        valor = valor.substring(0,i) + valor.substring(i+1,valor.length);
        i = -1;
      }
    }
    if(valor.length < 1){
      valor = "";
    }else if(valor.length > 3 && valor.length < 7){
      valor = valor.substring(0,3) + "." + valor.substring(3,valor.length);
    }else if(valor.length > 6 && valor.length < 10){
      valor = valor.substring(0,3) + "." + valor.substring(3,6) + "." + valor.substring(6,valor.length);
    }else if(valor.length > 9 && valor.length < 12){
      valor = valor.substring(0,3) + "." + valor.substring(3,6) + "." + valor.substring(6,9) + "-" + valor.substring(9,valor.length);
    }else if(valor.length > 11){
      valor = valor.substring(0,3) + "." + valor.substring(3,6) + "." + valor.substring(6,9) + "-" + valor.substring(9,11);
    }
    obj.value = valor;
    oldValor = valor;
    oldObj = obj;
  }
}

function validaCPF(obj)
{
    if (isEmpty(obj.value))
    {
        alert("Por favor informe seu número de CPF.");
        obj.focus();
        obj.select();
        return false;
    }
    else if (!isCPF(obj.value))
    {
        alert("O CPF informado é inválido.");
        obj.focus();
        obj.select();
        return false;
    }
    return true;
}

function validaCPFOnBlur(obj)
{
    if (isEmpty(obj.value))
    {
        
        document.getElementById("cpfvalido").className= "esconde";
        document.getElementById("cpfinvalido").className= "esconde";
        return false;
        
    }
    
    if (!isCPF(obj.value))
    {
        alert("O CPF informado é inválido.");

            
        document.getElementById("cpfinvalido").className= "invalido";
        document.getElementById("cpfvalido").className= "esconde";

    }
    
    else {
        
        document.getElementById("cpfvalido").className= "valido";
        document.getElementById("cpfinvalido").className= "esconde";
        
    }
    
    return true;
}

//-----------------------------------------------------------------------------
//-- Valida se o valor informado é vazio                                     --
//-----------------------------------------------------------------------------
function isEmpty(value)
{
    var str = trim(value);
    if (str != "")
    {
        return false;
    }
    return true;
}

function trim(str) 
{
    str = str.toString().replace(/\$|\ /g,'');
    return str;
}


function onlyNumber(field, evt, begin, end)
{
    var keycode = 0;
    
    if (window.event)
    {
        keycode = window.event.keyCode;
    }
    else if (evt)
    {
        keycode = evt.which;
    }
    
    if (keycode < (48 + begin) || keycode > (48 + end))
    {
        if (keycode == 8 || keycode == 0 || keycode == 9)
        {
            return true;
        }
        else
        {
            return false;
        }
    }
    else
    {
        return true;
    }
}


//######################################//
//## BEGIN: FUNÇÕES VALIDAÇÃO DE CPF  ##//
//######################################//
function isCPF(CNUMB)
{
  if(Verify(CNUMB))
  {
    return true;
  }
  else
  {
    return false;
  }
  return;
}

function ClearStr(str, c)
{
  while((cx=str.indexOf(c))!=-1)
  {
    str = str.substring(0,cx)+str.substring(cx+1);
  }
  return(str);
}

function ParseNumb(c)
{
  c=ClearStr(c,'-');
  c=ClearStr(c,'/');
  c=ClearStr(c,',');
  c=ClearStr(c,'.');
  c=ClearStr(c,'(');
  c=ClearStr(c,')');
  c=ClearStr(c,' ');
  if((parseFloat(c) / c != 1))
  {
    if(parseFloat(c) * c == 0)
    {
      return(c);
    }
    else
    {
      return(0);
    }
  }
  else
  {
    return(c);
  }
}

function Verify(CNUMB)
{
  CNUMB = ParseNumb(CNUMB);
  
    if ((CNUMB == '00000000000') || (CNUMB == '11111111111') || 
           (CNUMB == '22222222222') || (CNUMB == '33333333333') || 
           (CNUMB == '44444444444') || (CNUMB == '55555555555') || 
           (CNUMB == '66666666666') || (CNUMB == '77777777777') || 
           (CNUMB == '88888888888') || (CNUMB == '99999999999') || 
           (CNUMB == '01234567890') || (CNUMB == '12345678909'))
    {
        return false;
    }

  
  
  if(CNUMB == 0)
  {
    return(false);
  }
  else
  {
    g=CNUMB.length-2;
    if(TestDigit(CNUMB,g))
    {
      g=CNUMB.length-1;
      if(TestDigit(CNUMB,g))
      {    
        return(true);
      }
      else
      {
        return(false);
      }
    }
    else
    {
      return(false);
    }
  }

}

function TestDigit(CNUMB, g)
{
  var dig=0;
  var ind=2;
  for(fouz=g;fouz>0;fouz--)
  {
    dig += parseInt(CNUMB.charAt(fouz-1))*ind;
    ind++;
  }
  dig%=11;
  if(dig<2)
  {
    dig=0;
  }
  else
  {
    dig=11-dig;
  }
  if(dig!=parseInt(CNUMB.charAt(g)))
  {
    return(false);
  }
  else
  {
    return(true);
  }
}
//####################################//
//## END: FUNÇÕES VALIDAÇÃO DE CPF  ##//
//####################################//
    // Bloco CNPJ //
    function isNUMB(c) 
 { 
 if((cx=c.indexOf(","))!=-1) 
  { 
  c = c.substring(0,cx)+"."+c.substring(cx+1); 
  } 
 if((parseFloat(c) / c != 1)) 
  { 
  if(parseFloat(c) * c == 0) 
   { 
   return(1); 
   } 
  else 
   { 
   return(0); 
   } 
  } 
 else 
  { 
  return(1); 
  } 
 } 

function LIMP(c) 
 { 
 while((cx=c.indexOf("-"))!=-1) 
  { 
  c = c.substring(0,cx)+c.substring(cx+1); 
  } 
 while((cx=c.indexOf("/"))!=-1) 
  { 
  c = c.substring(0,cx)+c.substring(cx+1); 
  } 
 while((cx=c.indexOf(","))!=-1) 
  { 
  c = c.substring(0,cx)+c.substring(cx+1); 
  } 
 while((cx=c.indexOf("."))!=-1) 
  { 
  c = c.substring(0,cx)+c.substring(cx+1); 
  } 
 while((cx=c.indexOf("("))!=-1) 
  { 
  c = c.substring(0,cx)+c.substring(cx+1); 
  } 
 while((cx=c.indexOf(")"))!=-1) 
  { 
  c = c.substring(0,cx)+c.substring(cx+1); 
  } 
 while((cx=c.indexOf(" "))!=-1) 
  { 
  c = c.substring(0,cx)+c.substring(cx+1); 
  } 
 return(c); 
 } 

function VerifyCNPJ(CNPJ) 
 { 
 CNPJ = LIMP(CNPJ); 
 if(isNUMB(CNPJ) != 1) 
  { 
  return(0); 
  } 
 else 
  { 
  if(CNPJ == 0) 
   { 
   return(0); 
   } 
  else 
   { 
   g=CNPJ.length-2; 
   if(RealTestaCNPJ(CNPJ,g) == 1) 
    { 
    g=CNPJ.length-1; 
    if(RealTestaCNPJ(CNPJ,g) == 1) 
     { 
     return(1); 
     } 
    else 
     { 
     return(0); 
     } 
    } 
   else 
    { 
    return(0); 
    } 
   } 
  } 
 } 
function RealTestaCNPJ(CNPJ,g) 
 { 
 var VerCNPJ=0; 
 var ind=2; 
 var tam; 
 for(f=g;f>0;f--) 
  { 
  VerCNPJ+=parseInt(CNPJ.charAt(f-1))*ind; 
  if(ind>8) 
   { 
   ind=2; 
   } 
  else 
   { 
   ind++; 
   } 
  } 
  VerCNPJ%=11; 
  if(VerCNPJ==0 || VerCNPJ==1) 
   { 
   VerCNPJ=0; 
   } 
  else 
   { 
   VerCNPJ=11-VerCNPJ; 
   } 
 if(VerCNPJ!=parseInt(CNPJ.charAt(g))) 
  { 
  return(0); 
  } 
 else 
  { 
  return(1); 
  } 
 } 
  

  function FormataCGC(Form, Campo, TeclaPres) 
  { 
    var tecla = TeclaPres.keyCode; 
    var strCampo; 
    var vr; 
    var tam; 
    var TamanhoMaximo = 14; 
  
    eval("strCampo = document." + Form + "." + Campo); 
  
    vr = strCampo.value; 
    vr = vr.replace("/", ""); 
    vr = vr.replace("/", ""); 
    vr = vr.replace("/", ""); 
    vr = vr.replace(",", ""); 
    vr = vr.replace(".", ""); 
    vr = vr.replace(".", ""); 
    vr = vr.replace(".", ""); 
    vr = vr.replace(".", ""); 
    vr = vr.replace(".", ""); 
    vr = vr.replace(".", ""); 
    vr = vr.replace(".", ""); 
    vr = vr.replace("-", ""); 
    vr = vr.replace("-", ""); 
    vr = vr.replace("-", ""); 
    vr = vr.replace("-", ""); 
    vr = vr.replace("-", ""); 
    tam = vr.length; 

    if (tam < TamanhoMaximo && tecla != 8) 
    { 
      tam = vr.length + 1; 
    } 

    if (tecla == 8) 
    { 
      tam = tam - 1; 
    } 

    if (tecla == 8 || tecla >= 48 && tecla <= 57 || tecla >= 96 && tecla <= 105) 
    { 
      if (tam <= 2) 
      { 
        strCampo.value = vr; 
      } 
       if ((tam > 2) && (tam <= 6)) 
       { 
         strCampo.value = vr.substr(0, tam - 2) + '-' + vr.substr(tam - 2, tam); 
       } 
       if ((tam >= 7) && (tam <= 9)) 
       { 
         strCampo.value = vr.substr(0, tam - 6) + '/' + vr.substr(tam - 6, 4) + '-' + vr.substr(tam - 2, tam); 
      } 
       if ((tam >= 10) && (tam <= 12)) 
       { 
         strCampo.value = vr.substr(0, tam - 9) + '.' + vr.substr(tam - 9, 3) + '/' + vr.substr(tam - 6, 4) + '-' + vr.substr(tam - 2, tam); 
      } 
       if ((tam >= 13) && (tam <= 14)) 
       { 
         strCampo.value = vr.substr(0, tam - 12) + '.' + vr.substr(tam - 12, 3) + '.' + vr.substr(tam - 9, 3) + '/' + vr.substr(tam - 6, 4) + '-' + vr.substr(tam - 2, tam); 
      } 
       if ((tam >= 15) && (tam <= 17)) 
       { 
         strCampo.value = vr.substr(0, tam - 14) + '.' + vr.substr(tam - 14, 3) + '.' + vr.substr(tam - 11, 3) + '.' + vr.substr(tam - 8, 3) + '.' + vr.substr(tam - 5, 3) + '-' + vr.substr(tam - 2, tam); 

      } 
    } 
  } 


function TESTA() 
 { 
 if (document.forms[0].CNPJ.value != "" || null || undefined) { 

 if(VerifyCNPJ(document.forms[0].CNPJ.value) == 1)  
  
  { 
  alert("CNPJ válido!");
  return true 
  } 
 else 
  { 
  alert("CNPJ não é válido!"); 
  return false
  } 
 document.forms[0].CNPJ.focus(); 
 return; 
 }

  }
 // fim do bloco cnpj //                
</script>
</head>
<body>
<form name="Form" method="post" action="">
  <p>
    <select name="opcao" id="opcao" onChange="alteraMascara();">
      <option>Selecione</option>
      <option value="fisica">Pessoa F&iacute;sica</option>
      <option value="juridica">Pessoa Jur&iacute;dica</option>
    </select>
  </p>
  <div id="divcpf" class="esconde">
  CPF: <input name="cpf" class="textbox" id="cpf" onblur="validaCPFOnBlur(this);" onkeydown="checaCPF(this);" onkeyup="checaCPF(this);" size="16" maxLength="14">
    <input type="image" hidden src="clientes/imagens/cpfvalido.gif" name="cpfvalido" id="cpfvalido" class="esconde">
    <input type="image" hidden  src="clientes/imagens/cpfinvalido.gif" name="cpfinvalido" id="cpfinvalido" class="esconde">
  </div>
  <div id="divcnpj" class="esconde">
  CNPJ: <input type='text' maxlength=18 name='CNPJ' onFocus='this.select();' onKeyUp="FormataCGC('Form', 'CNPJ', event);" onBlur="TESTA();">
      <input type="image" hidden src="clientes/imagens/cpfvalido.gif" name="cnpjvalido" id="cnpjvalido" class="esconde">
    <input type="image" hidden  src="clientes/imagens/cpfinvalido.gif" name="cnpjinvalido" id="cnjpinvalido" class="esconde"></div>
</form>
</body>
</html>

Editado por Gutto
Link para o comentário
Compartilhar em outros sites

  • 0
Guest saga_fuel

As funções são grandes mais são uteis...................

mais resumindo então, não tem como eu mudar o evento de um componente html em tempo de execução????

O javascript não permite isso ??

Link para o comentário
Compartilhar em outros sites

  • 0

Seria algo deste tipo:

<html>
<head>
&lt;script type="text/javascript">
function altera_opcao(opcao)
{
    switch (opcao)
    {
        case '1':
            document.getElementById('teste1').onkeypress = new Function("event","return txtBoxFormat(this.form, this.name, '999.999.999-99', event);");
            break;
        case '2':
            document.getElementById('teste1').onkeypress = new Function("event","return txtBoxFormat(this.form, this.name, '99.999.999/9999-99', event);");
    }
}

function txtBoxFormat(formulario,nome,formato,evento)
{
    alert(formato);
}
</script>
</head>
<body>
<form>
<select id="teste" name="select_1" onchange="altera_opcao(this.value)">
<option value="1">Pessoa física</option>
<option value="2">Pessoa jurídica</option>
</select>
<input type="text" id="teste1" name="input_1" value="" onkeypress="return txtBoxFormat(this.form, this.name, '999.999.999-99', event);">
</form>
</body>
</html>

Link para o comentário
Compartilhar em outros sites

  • 0
Guest SAGA_FUEL

Galera não funciouna.....olha eu uso o seguinte codigo,e não acontece nada nem da erro de script, pra validar se estava passando eu utilizei o alter e realmente funciouna.............estrainho nééé??

alguém tem algum chute?

function MudaEvento(){

if (this.vmfinancas.TIPO.value =='J' ){

// document.getElementById("CPF").onKeyPress ="return txtBoxFormat(this.form, this.name, '99.999.999/9999-99', event);";

document.getElementById("CPF").onKeyPress = new Function("event","return txtBoxFormat(this.form, this.name, '99.999.999/9999-99', event);");

// alert("j");

}

else if (this.vmfinancas.TIPO.value == 'F') {

document.getElementById("CPF").onKeyPress = new Function("event","return txtBoxFormat(this.form, this.name, '999.999.999-99', event);");

// alert("f");

}

}

Link para o comentário
Compartilhar em outros sites

Participe da discussão

Você pode postar agora e se registrar depois. Se você já tem uma conta, acesse agora para postar com sua conta.

Visitante
Responder esta pergunta...

×   Você colou conteúdo com formatação.   Remover formatação

  Apenas 75 emoticons são permitidos.

×   Seu link foi incorporado automaticamente.   Exibir como um link em vez disso

×   Seu conteúdo anterior foi restaurado.   Limpar Editor

×   Você não pode colar imagens diretamente. Carregar ou inserir imagens do URL.



  • Estatísticas dos Fóruns

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