Ajuda com JavaScript

2 respostas
oliveirarenan

Pessoal…

Não manjo muito de JS…

tentei implementar o q o diego postou aqui, mas não rodou…alguém tem alguma sugestão???

<html>

<head>

	<title>Documento sem t&iacute;tulo</title>
	<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
	<link href="C:DsvBradescostyleestilosApp.css" rel="stylesheet" type="text/css">
	<link href="C:DsvBradescostyleestilos.css" rel="stylesheet" type="text/css">

<script language = "JavaScript">
	
	//Verifica qual o browser do visitante e armazena na variável púbica clientNavigator, 
	//Caso Internet Explorer(IE) outros (Other) 
	if (navigator.appName.indexOf('Micro$oft') != -1){ 
	   clientNavigator = "IE"; 
	}else{ 
	   clientNavigator = "Other"; 
	}
	
	function Verifica_Data(data, obrigatorio)
	{ 
		//Se o parâmetro obrigatório for igual à zero, significa que elepode estar vazio, caso contrário, não 
		var data = document.getElementById(data); 
		var strdata = data.value; 
	   
		if((obrigatorio == 1) || (obrigatorio == 0 && strdata != ""))
		{ 
		  //Verifica a quantidade de digitos informada esta correta. 
		  if (strdata.length != 10){ 
			 alert("Formato da data não é válido. Formato correto: dd/mm/aaaa."); 
			 data.focus();
			 return false 
		  }
		  
		  //Verifica máscara da data 
		  if ("/" != strdata.substr(2,1) || "/" != strdata.substr(5,1))
		  { 
			 alert("Formato da data não é válido. Formato correto: dd/mm/aaaa."); 
			 data.focus(); 
			 return false 
		  } 
		  
		  dia = strdata.substr(0,2) 
		  mes = strdata.substr(3,2); 
		  ano = strdata.substr(6,4); 
		  
		  //Verifica o dia 
		  if (isNaN(dia) || dia > 31 || dia < 1)
		  { 
			 alert("Formato do dia não é válido."); 
			 data.focus(); 
			 return false 
		  }
		   
		  if (mes == 4 || mes == 6 || mes == 9 || mes == 11)
		  { 
			 if (dia == "31")
			 { 
				alert("O mês informado não possui 31 dias."); 
				data.focus(); 
				return false 
			 } 
		  }
		   
		  if (mes == "02")
		  { 
			 bissexto = ano % 4; 
			 if (bissexto == 0)
			 { 
				if (dia > 29)
				{ 
				   alert("O mês informado possui somente 29 dias."); 
				   data.focus(); 
				   return false 
				} 
			 }
			 else
			 { 
				if (dia > 28)
				{ 
				   alert("O mês informado possui somente 28 dias."); 
				   data.focus(); 
				   return false 
				} 
			 } 
		  } 
	   	  
		  //Verifica o mês 
		  if (isNaN(mes) || mes > 12 || mes < 1)
		  { 
			 alert("Formato do mês não é válido."); 
			 data.focus(); 
			 return false 
		  } 
		  
		  //Verifica o ano 
		  if (isNaN(ano))
		  { 
			 alert("Formato do ano não é válido."); 
			 data.focus(); 
			 return false 
		  } 
	   }
} 

	
	function Compara_Datas(data_inicial, data_final)
	{ 
	   //Verifica se a data inicial é maior que a data final 
	   var data_inicial = document.getElementById(data_inicial); 
	   var data_final   = document.getElementById(data_final); 
	   str_data_inicial = data_inicial.value; 
	   str_data_final   = data_final.value; 
	   dia_inicial      = data_inicial.value.substr(0,2); 
	   dia_final        = data_final.value.substr(0,2); 
	   mes_inicial      = data_inicial.value.substr(3,2); 
	   mes_final        = data_final.value.substr(3,2); 
	   ano_inicial      = data_inicial.value.substr(6,4); 
	   ano_final        = data_final.value.substr(6,4); 
	   if(ano_inicial > ano_final){ 
		  alert("A data inicial deve ser menor que a data final."); 
		  data_inicial.focus(); 
		  return false 
	   }else{ 
	   if(ano_inicial == ano_final){ 
		 if(mes_inicial > mes_final){ 
		  alert("A data inicial deve ser menor que a data final."); 
				data_final.focus(); 
				return false 
			 }else{ 
				if(mes_inicial == mes_final){ 
				   if(dia_inicial > dia_final){ 
					  alert("A data inicial deve ser menor que a data final."); 
					  data_final.focus(); 
					  return false 
				   } 
				} 
			 } 
		  } 
	   } 
	} 
	
	function Ajusta_Data(input, evnt)
	{ 
		//Ajusta máscara de Data e  permite digitação de números 
		   if (input.value.length == 2 || input.value.length == 5){ 
			  if(clientNavigator == "IE"){ 
				 input.value += "/"; 
			  }else{ 
				 if(evnt.keyCode == 0){ 
					input.value += "/"; 
				 } 
			  } 
		   }
		 //Chama a função Bloqueia_Caracteres para  permitir a digitação de números 
		return Bloqueia_Caracteres(evnt); 
	}
	
	

	// Verifica foi inserido algum campo na tela
	function verificaInsercao()
	{	
		if ((document.forms[0].txtCodCamp.value == '' ) &&
			(document.forms[0].txtNomeCamp.value == '' ) &&
			(document.forms[0].txaDescricao.value == '' ) &&
			(document.forms[0].txtCodCanal.value == '' ) &&
			(document.forms[0].txtCodProd.value == '' ) &&
			(document.forms[0].txtNomeProd.value == '' ) &&
			(document.forms[0].txtUrl.value == '' ) &&
			(document.forms[0].txtModularidade.value == '' ))
			{
				alert('Não  dados a serem inseridos!' );
				document.frm.txtCodCamp.focus();
				return false;
			}
			else
			{
				verificaDados();
			}
	}

	// Valida se os campos foram preenchidos
	function verificaDados()
	{
		var nomeCamp = 'Nome da Campanha';
		var descricao = 'Descrição da Campanha';
		var codCanal = 'Código do Canal';
		var dataInicio = 'Data de Inicio da Campanha';
		var dataTermino = 'Data de Término da Campanha';
		var produto = 'Código do Produto da Campanha';
		var nomeProduto = 'Nome do Produto da Campanha';
		var modalidade = 'Código da Modalidade';
		var nomeModalidade = 'Nome da Modalidade';
		var url = "URL da Campanha";
		
			if (document.forms[0].txtNomeCamp.value == '' )
			{
				alert('Campo ' + nomeCamp + ' não preenchido!');
				document.frm.txtNomeCamp.focus();
			}
			else
				if (document.forms[0].txaDescricao.value == '' )
				{
					alert('Campo ' + descricao + ' não preenchido!');	
					document.frm.txaDescricao.focus();
				}
				else
					if (document.forms[0].data_inicial.value == '' )
					{
						alert('Campo ' + dataInicio + ' não preenchido!');
						document.frm.data_inicial.focus();
					}
					else
						if (document.forms[0].data_termino.value == '' )
						{
							alert('Campo ' + dataTermino + ' não preenchido!');
							document.frm.data_termino.focus();	
						}
						else
							if (document.forms[0].txtCodCanal.value == '' )
							{
								alert('Campo ' + codCanal + ' não preenchido!');
								document.frm.txtCodCanal.focus();	
							}	
							else
								if (document.forms[0].txtCodProd.value == '' )
								{
									alert('Campo ' + produto + ' não preenchido!');
									document.frm.txtCodProd.focus();	
								}
								else
									if (document.forms[0].txtNomeProd.value == '' )
									{
										alert('Campo ' + nomeProduto + ' não preenchido!');
										document.frm.txtNomeProd.focus();											
									}
									else
										if (document.forms[0].txtUrl.value == '' )
										{
											alert('Campo ' + url + ' não preenchido!');
											document.frm.txtUrl.focus();
										}
										else
											if (document.forms[0].txtNomeModularidade.value == '' )
											{
												alert('Campo ' + nomeModularidade + ' não preenchido!');
												document.frm.txtNomeModularidade.focus();	
											}
											else
												if (document.forms[0].txtModularidade.value == '' )
												{
													alert('Campo ' + modularidade + ' não preenchido!');
													document.frm.txtModularidade.focus();
												}
												else
												{
													alert('Registro Cadastrado com sucesso!');
													limpaCampos();
													document.frm.txtCodCamp.focus();
												}
	}
	
	// limpa os valores dos campos na tela
	function limpaCampos()
	{
		document.forms[0].txtCodCamp.value = '';
		document.forms[0].txtNomeCamp.value = '';
		document.forms[0].txaDescricao.value = '';
		document.forms[0].txtCodCanal.value = '';
		document.forms[0].data_termino.value = '   /    / ';
		document.forms[0].data_inicial.value = '   /    / ';
		document.forms[0].txtCodProd.value = '';
		document.forms[0].txtNomeProd.value = '';
		document.forms[0].txtUrl.value = '';
		document.forms[0].txtModularidade.value = '';
		document.forms[0].txtNomeModularidade.value = '';
		document.frm.txtCodCamp.focus();
	}

</script>

</head>

<body class="fnd1" id=bodytag scroll=no>
	
		<table width="1019" border="0">
		  <tr>
		    <td width="1013" height="394" valign="top">
			<form name="frm" method="post" action="">
		        <table width="99%" border="0">
		          	<tr>
		          	  <td height="31" class="lbl1">&nbsp;</td>
		          	  <td>&nbsp;</td>
		          	  <td class="lbl1">&nbsp;</td>
		          	  <td>&nbsp;</td>
	          	  </tr>
		          	<tr>
			            <td width="15%" height="31" class="lbl1"><p><b>Código:</b></p></td>
			            <td width="13%"><input name="txtCodCamp" type="text" class="frmTxt1" id="txtCodCamp22" value="" size="15" maxlength="6" ></td>
			            <td width="9%" class="lbl1"><b>Nome:</b></td>
			            <td width="63%"><input name="txtNomeCamp" type="text" class="frmTxt1" id="txtNomeCamp" size="70" maxlength="25" ></td>
		  			</tr>
        		</table>
        		
        		<table width="99%" height="85" border="0"> 
          			<tr>
            			<td width="15%" height="35" class="lbl1"><b>Descrição:</b></td>
			            <td width="85%" rowspan="3" class="frmCmb1"><textarea name="txaDescricao" cols="105" rows="5" id="textarea19" style="overflow:auto" class="frmTxtArea1" ></textarea></td>
          			</tr>
          
          			<tr>
            			<td class="txtTab1">&nbsp;</td>
          			</tr>
					
					<tr>
            			<td height="21" class="txtTab1">&nbsp;</td>
          			</tr>
       		  </table>
        		
        		<table width="89%" border="0">

          			<tr>
            			<td height="330" class="lbl1"><table width="99%" border="0">
                          <tr>
                            <td width="17%" height="33" class="lbl1"><b>C&oacute;digo Canal:</b></td>
                            <td width="14%"><input name="txtCodCanal" type="text" class="frmtxt1" id="txtCodCanal3" value="" size="10" maxlength="2" ></td>
                            <td width="16%" class="lbl1"><b>Status:</b></td>
                            <td width="17%">
							<select name="cbxStatus" size="1" class="frmCmb1" id="select6" >
                              <option value="1" selected>Ativo
                              <option value="2">Inativo
                            </select></td>
                            <td width="20%" class="lbl1"><b>Prioridade:</b></td>
                            <td width="16%"><select name="cbxPrioridade" size="1" class="frmCmb1" id="select7" >
                              <option value="1" selected>Alta
                              <option value="2">M&eacute;dia
                              <option value="3">Baixa
                            </select>
</td>
                          </tr>
                          <tr>
                            <td class="lbl1"><b>Data de Início:</b></td>
                            <td>
								<input name="data_inicial" type="text" class="frmtxt1" id="data_inicial" maxlength="10" size="15" onFocus="Verifica_Data(data, obrigatorio)"> 
                            </td>
                            <td height="34" class="lbl1"><b>Data de T&eacute;rmino:</b></td>
                            <td>
								<input name="data_termino" type="text" class="frmtxt1" id="data_termino" maxlength="10" size="15"> 
							</td>
                            <td class="lbl1"><b>Status da Ag&ecirc;ncia:</b></td>
                            <td><select name="cbxStatusAgencia" size="1" class="frmCmb1" id="select8" >
                              <option selected>Ativo
                              <option>Inativo
                            </select>
</td>
                          </tr>
                        </table>            			  <b>&nbsp;</b>
                        <table width="100%" border="0">
                          <tr>
                            <td width="68%" height="43"><table width="100%" border="0">
                                <tr>
                                  <td width="25%" height="24" class="lbl1"><b>Produto:&nbsp;</b></td>
                                  <td width="13%"><b>
                                    <input name="txtCodProd" type="text" class="frmTxt1" id="txtCodProd11" value="" size="10" maxlength="2" >
                                  </b></td>
                                  <td width="62%"><b>
                                    <input name="txtNomeProd" type="text" class="frmTxt1" id="txtNomeProd11" value="" size="55" maxlength="25" >
                                  </b></td>
                                </tr>
                              </table>
                            </td>
                            <td width="32%"><table width="98%" border="0">
                                <tr>
                                  <td width="40%" height="26" class="lbl1"><b>&nbsp;N&iacute;vel
                                      Usu&aacute;rio:</b></td>
                                  <td width="60%"><select name="cbxNivelUsuario" size="1" class="frmCmb1" id="select13" >
                                      <option selected>Pr&eacute;-Atendente
                                      <option>Gerente
                                    </select>
                                  </td>
                                </tr>
                              </table>
                            </td>
                          </tr>
                        </table>
                        <b> </b>
                        <table width="97%" border="0">
                          <tr>
                            <td width="18%" height="36" class="lbl1"><b>Modularidade:</b></td>
                            <td width="8%"><input name="txtModularidade" type="text" class="frmtxt1" id="txtModularidade3" value="" size="10" maxlength="2" >
                            </td>
                            <td width="74%"><input name="txtNomeModularidade" type="text" class="frmtxt1" id="txtNomeModularidade2" value="" size="55" maxlength="2" >
                            </td>
                          </tr>
                        </table>
                        <table width="99%" border="0">
                          <tr>
                            <td width="17%" height="30" class="lbl1"><b>Perfil Cliente:</b></td>
                            <td width="31%"><select name="cbxPerfil" size="1" class="frmCmb1" id="select14" >
                              <option selected>Titular e Dependente
                              <option>Titular
                              <option>Dependente
                            </select></td>
                            <td width="6%" class="lbl1"><b>URL:</b></td>
                            <td width="46%"><input name="txtUrl" type="text" class="frmTxt1" id="txtUrl2" value="" size="58" ></td>
                          </tr>
                      </table>
					  <center>                     
                        <table width="21%" height="82" border="0">
                          <tr>
                            <td width="39%" height="39"><input name="btnSalvar" type="button" class="bto1" id="btnSalvar2" value="Salvar" onClick="verificaInsercao();"></td>
                            <td width="61%"><p align="right"><input name="btnCancelar" type="button" class="bto1" id="btnCancelar3" value="Cancelar" onClick="location.href('inicial.htm')"></p></td>
                          </tr>
                      </table>
					  </center>                        <p>&nbsp;</p></td>
           			</tr>
        		</table>
        
               	</form>
    </td>
  </tr>
</table>

</body>

</html>

Qualquer ajuda é sempre bem vinda…

valeu!!! []

Renan

2 Respostas

D

Aparentemente, o erro está em:

<input name="data_inicial" type="text" class="frmtxt1" id="data_inicial" maxlength="10" size="15" onFocus="Verifica_Data(data, obrigatorio)">

Onde o onFocus… chama o Javascript.
Os parametros data e obrigatorio devem ser Strings ou seja, “data” e “obrigatorio”.

Como o id deste campo é data_inicial, ou vc usa “data_inicial” no primeiro parametro ou só o this.

Agora se o erro não era quando clicava no campo “Data de Inicio”, eu num sei! :slight_smile:

[]'s

plentz

oliveirarenan, da uma olhada melhor lá no tópico, lá tem alguns esclarecimentos e dicas na parte de baixo do código. Recomendo tu NUNCA colocar a função inteira dentro do código. Crie um arquivo .js e depois só faça referência dele em suas páginas…evita redundância e fica + organizado ;). Sobre o detalhe que nosso amigo disse aqui em cima…a função Verfica_Data, deve ser usada somente na hora de enviar o formulário, e nunca no onFocus(). No campo input, recomendo que você só coloque a função Ajusta_Data, sendo que para usá-la é só seguir as intruções que coloquei ali no outro tópico. E verifique também os parâmetros que voc~es está passando para a função, pois não estão corretos :wink:

Criado 12 de agosto de 2004
Ultima resposta 13 de ago. de 2004
Respostas 2
Participantes 3