Ir para conteúdo

POWERED BY:

Arquivado

Este tópico foi arquivado e está fechado para novas respostas.

Rodrigo Vieira E da Silva

validação JavaScript

Recommended Posts

Bom dia a todos do fórum.

 

É o seguinte estou a 2 dias tentando resolver um mistério para mim é um desafio, acredito que muitos aqui já passaram por isso.

 

Vamos lá.

 

Eu tenho uma pagina em html e dentro desta pagina eu tenho um iframe contendo um formulário.

 

Nesta página eu tenho também um formulário com apenas um campo.

 

O formulário que esta no iframe já esta validado, ao clicar no botão adicionar ele faz a verificação dos campos.

 

O Botão gerar os também esta validado, referente o campo OBSERVAÇÃO.

 

A Dúvida é a seguinte eu preciso fazer uma terceira validação que é quando a pessoa clicar no botão GERAR ele verifica se os campos do iframe esta vazio.

 

Estou mandando uma jpg para todos analisar.

 

Bem vindos a esse desafio.

 

teste.jpg

Compartilhar este post


Link para o post
Compartilhar em outros sites

@Rodrigo Vieira E da Silva, bom dia

 

Vc só pode chamar de "desafio" se vc souber a resposta.

Até lá, é apenas uma dúvida sua. Alterei o título do tópico para obedecer as regras do fórum.

 

Sobre sua dúvida, leia esses posts:

http://wbruno.com.br/javascript-puro/acessar-funcao-de-um-iframe-apatir-documento-pai/

http://wbruno.com.br/javascript-puro/pegar-de-iframe-jogar-documento-pai/

 

ai eu mostro como acessar o iframe, basta aplicar ao seu caso.

Compartilhar este post


Link para o post
Compartilhar em outros sites

Bruno, muito obrigado por pela a dica do titulo do post.

 

Então mais entrei no link que você enviou e não consegui compreender.

 

Se eu te mandar o códgio do projeto você me explica melhor.

 

Att.,

 

 

Código do iframe

<?php session_start(); ?>
<?php require_once('../connections/conihouse.php'); ?>
<?php
if (!function_exists("GetSQLValueString")) {
function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "")
{
if (PHP_VERSION < 6) {
$theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;
}

$theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue);

switch ($theType) {
case "text":
$theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
break;
case "long":
case "int":
$theValue = ($theValue != "") ? intval($theValue) : "NULL";
break;
case "double":
$theValue = ($theValue != "") ? doubleval($theValue) : "NULL";
break;
case "date":
$theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
break;
case "defined":
$theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
break;
}
return $theValue;
}
}

$editFormAction = $_SERVER['PHP_SELF'];
if (isset($_SERVER['QUERY_STRING'])) {
$editFormAction .= "?" . htmlentities($_SERVER['QUERY_STRING']);
}

if ((isset($_POST["MM_insert"])) && ($_POST["MM_insert"] == "defeito")) {
$insertSQL = sprintf("INSERT INTO defeito (defeito_os_id, defeito_produto_id, defeito_revenda_id, defeito_ns, defeito_nf, defeito_descricao) VALUES (%s, %s, %s, %s, %s, %s)",
GetSQLValueString($_POST['id_defeito'], "text"),
GetSQLValueString($_POST['produto'], "int"),
GetSQLValueString($_POST['revenda'], "int"),
GetSQLValueString($_POST['numero_serie'], "text"),
GetSQLValueString($_POST['nota_fiscal'], "text"),
GetSQLValueString($_POST['defeito'], "text"));

mysql_select_db($database_conihouse, $conihouse);
$Result1 = mysql_query($insertSQL, $conihouse) or die(mysql_error());

$insertGoTo = "lista-de-produtos.php?atualizar=" . $_SESSION['id_defeito'] . "";
if (isset($_SERVER['QUERY_STRING'])) {
$insertGoTo .= (strpos($insertGoTo, '?')) ? "&" : "?";
$insertGoTo .= $_SERVER['QUERY_STRING'];
}
header(sprintf("Location: %s", $insertGoTo));
}

mysql_select_db($database_conihouse, $conihouse);
$query_rs_produto = "SELECT produtos_id, produto_nome FROM produtos ORDER BY produto_nome DESC";
$rs_produto = mysql_query($query_rs_produto, $conihouse) or die(mysql_error());
$row_rs_produto = mysql_fetch_assoc($rs_produto);
$totalRows_rs_produto = mysql_num_rows($rs_produto);

$colname_rs_lista = "-1";
if (isset($_GET['atualizar'])) {
$colname_rs_lista = $_GET['atualizar'];
}
mysql_select_db($database_conihouse, $conihouse);
$query_rs_lista = sprintf("SELECT defeito.defeito_id, defeito.defeito_os_id, defeito.defeito_produto_id, produtos.produto_nome, defeito.defeito_ns, defeito.defeito_nf, defeito.defeito_descricao FROM (defeito LEFT JOIN produtos ON produtos.produtos_id=defeito.defeito_produto_id) WHERE defeito_os_id = %s", GetSQLValueString($colname_rs_lista, "text"));
$rs_lista = mysql_query($query_rs_lista, $conihouse) or die(mysql_error());
$row_rs_lista = mysql_fetch_assoc($rs_lista);
$totalRows_rs_lista = mysql_num_rows($rs_lista);

?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "[url=http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd]http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd [/url]">
<html xmlns="[url=http://www.w3.org/1999/xhtml]http://www.w3.org/1999/xhtml [/url]">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Lista de Produtos com Defeito</title>
<style type="text/css">
<!--
body { margin: 0px; padding: 0px}
#main { width: 900px; font:normal 14px Arial, Helvetica, sans-serif; }
#main #cola { width: 858px; padding-right: 29px; padding-left: 13px;}
#main #cola #frmdefeito p label { float: left; width: 175px; }
#main #cola #frmdefeito p #produto { border: 1px solid #517087; padding:5px }
#main #cola #frmdefeito p .campos { border: 1px solid #517087; padding:5px; width:669px; margin-left:2px; color:#666; }
#main #cola #frmdefeito p .campos:focus {color:#FFF; background:#036;}
#main #cola #frmdefeito p #defeito { border: 1px solid #517087; padding:5px; width:848px; color:#666; }
#main #cola #frmdefeito p #defeito:focus {color:#FFF; background:#036;}
#main #cola #frmdefeito p #btnenviar { font-family: Arial, Helvetica, sans-serif; color: #FFF; background: #45637A; padding: 7px 10px; font-weight: bold; border-style: none; cursor:pointer}
#main #colb {width: 818px; padding-right: 29px; padding-left: 13px; height: 125px; overflow:auto; border: solid 1px #ccc; margin-left:13px; background:#FFC; }
-->
</style>
<script type="text/javascript">
<!--
function MM_validateForm() { //v4.0
if (document.getElementById){
var i,p,q,nm,test,num,min,max,errors='',args=MM_validateForm.arguments;
for (i=0; i<(args.length-2); i+=3) { test=args[i+2]; val=document.getElementById(args[i]);
if (val) { nm=val.name; if ((val=val.value)!="") {
if (test.indexOf('isEmail')!=-1) { p=val.indexOf('@');
if (p<1 || p==(val.length-1)) errors+='- '+nm+' must contain an e-mail address.\n';
} else if (test!='R') { num = parseFloat(val);
if (isNaN(val)) errors+='O campo '+nm+' somente é permitido números.\n';
if (test.indexOf('inRange') != -1) { p=test.indexOf(':');
min=test.substring(8,p); max=test.substring(p+1);
if (num<min || max<num) errors+='- '+nm+' must contain a number between '+min+' and '+max+'.\n';
} } } else if (test.charAt(0) == 'R') errors += 'O campo '+nm+' é obrigatório.\n'; }
} if (errors) alert('Verifique os seguintes erros:\n'+errors);
document.MM_returnValue = (errors == '');
} }
//-->
</script>
<script type="text/javascript">

function validaCampo(op) {

if(op=="Selecione o produto") {

alert("Selecione o produto");

return false;

} else

return true;

}

</script>
</head>
<body>
<div id="main">
<div id="cola">
<form name="defeito" method="POST" action="<?php echo $editFormAction; ?>" id="frmdefeito">
<p>
<label><strong>Produto</strong></label>
<select name="produto" id="produto">
<option value="" selected="selected">Selecione o produto</option>
<?php do { ?>
<option value="<?php echo $row_rs_produto['produtos_id']?>"><?php echo $row_rs_produto['produto_nome']?></option>
<?php } while ($row_rs_produto = mysql_fetch_assoc($rs_produto));
$rows = mysql_num_rows($rs_produto);
if($rows > 0) { mysql_data_seek($rs_produto, 0);
$row_rs_produto = mysql_fetch_assoc($rs_produto); } ?>
<option value="Outro" value="Outro">Outro</option>
</select>
</p>
<p><label><strong>Número de Série</strong></label><input name="numero_serie" type="text" class="campos" id="numero_serie" onfocus="if(this.value=='Insira o número de Série')this.value='';" value="Insira o número de Série" maxlength="40" /></p>
<p><label><strong>Nota Fiscal de Compra</strong></label><input name="nota_fiscal" type="text" class="campos" id="nota_fiscal" onfocus="if(this.value=='Insira o número da nota fiscal de compra')this.value='';" value="Insira o número da nota fiscal de compra" maxlength="40" /></p>
<p><label><strong>Defeito</strong></label><br /><textarea name="defeito" id="defeito" cols="45" rows="5" onfocus="if(this.value=='Insira neste campo o defeito que apresenta no produto.')this.value='';" style="font-family:Arial, Helvetica, sans-serif">Insira neste campo o defeito que apresenta no produto.</textarea></p>
<p><input name="Enviar" type="submit" id="btnenviar" title="Adicionar a lista" onclick="MM_validateForm('numero_serie','','RisNum','nota_fiscal','','RisNum','defeito','','R','produto','','R');return document.MM_returnValue" value="ADICIONAR" /><input name="id_defeito" type="hidden" id="id_defeito" value="<?php echo $_SESSION['id_defeito']; ?>" /><input type="hidden" name="MM_insert" value="defeito" /></p>
<input name="revenda" type="hidden" value="<?php echo $_SESSION['revenda']; ?>" />
</form>
</div>
<div id="colb">
<?php do { ?>
<p>
<strong>Produto: </strong><?php echo $row_rs_lista['produto_nome']; ?><br />
<strong>Número de Série: </strong><?php echo $row_rs_lista['defeito_ns']; ?><br />
<strong>Nota Fiscal: </strong><?php echo $row_rs_lista['defeito_nf']; ?><br />
<strong>Defeito:</strong><br /><?php echo $row_rs_lista['defeito_descricao']; ?>
</p>
<hr />
<?php } while ($row_rs_lista = mysql_fetch_assoc($rs_lista)); ?>
</div>
</div>
</body>
</html>
<?php mysql_free_result($rs_produto); mysql_free_result($rs_lista); ?>[/i]
 
 
 
 
 
CODIGO DA PAGINA
<?php require_once('../connections/conihouse.php'); ?>
<?php
session_start();
 
// Load the tNG classes
require_once('../includes/tng/tNG.inc.php');
 
// Make unified connection variable
$conn_conihouse = new KT_connection($conihouse, $database_conihouse);
 
//Start Restrict Access To Page
$restrict = new tNG_RestrictAccess($conn_conihouse, "../");
//Grand Levels: Level
$restrict->addLevel("Master");
$restrict->Execute();
//End Restrict Access To Page
 
 
if (!function_exists("GetSQLValueString")) {
function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") 
{
  if (PHP_VERSION < 6) {
    $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;
  }
 
  $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue);
 
  switch ($theType) {
    case "text":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;    
    case "long":
    case "int":
      $theValue = ($theValue != "") ? intval($theValue) : "NULL";
      break;
    case "double":
      $theValue = ($theValue != "") ? doubleval($theValue) : "NULL";
      break;
    case "date":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;
    case "defined":
      $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
      break;
  }
  return $theValue;
}
}
 
$editFormAction = $_SERVER['PHP_SELF'];
if (isset($_SERVER['QUERY_STRING'])) {
  $editFormAction .= "?" . htmlentities($_SERVER['QUERY_STRING']);
}
 
if ((isset($_POST["MM_insert"])) && ($_POST["MM_insert"] == "os")) {
  $insertSQL = sprintf("INSERT INTO os (os_data, os_mes, os_ano, os_usuario_loja_id, os_usuario_revenda_id, os_defeito_os_id, os_observacoes) VALUES (%s, %s, %s, %s, %s, %s, %s)",
                       GetSQLValueString($_POST['data'], "text"),
                       GetSQLValueString($_POST['mes'], "int"),
                       GetSQLValueString($_POST['ano'], "text"),
                       GetSQLValueString($_POST['revenda'], "int"),
                       GetSQLValueString($_POST['usuario'], "int"),
                       GetSQLValueString($_POST['defeito'], "text"),
                       GetSQLValueString($_POST['observacoes'], "text"));
 
  mysql_select_db($database_conihouse, $conihouse);
  $Result1 = mysql_query($insertSQL, $conihouse) or die(mysql_error());
 
  $insertGoTo = "abertura-ordem-de-servicos.php";
  if (isset($_SERVER['QUERY_STRING'])) {
    $insertGoTo .= (strpos($insertGoTo, '?')) ? "&" : "?";
    $insertGoTo .= $_SERVER['QUERY_STRING'];
  }
  header(sprintf("Location: %s", $insertGoTo));
printf("Last inserted record has id %d\n", mysql_insert_id());
}
 
$colname_rs_rev = "-1";
if (isset($_SESSION['revenda'])) {
  $colname_rs_rev = $_SESSION['revenda'];
}
mysql_select_db($database_conihouse, $conihouse);
$query_rs_rev = sprintf("SELECT revendedores_id, revendedores_empresa, revendedores_cnpj, revendedores_inscricao_estadual, revendedores_endereco, revendedores_bairro, revendedores_cidades, revendedores_uf, revendedores_cep FROM revendedores WHERE revendedores_id = %s", GetSQLValueString($colname_rs_rev, "int"));
$rs_rev = mysql_query($query_rs_rev, $conihouse) or die(mysql_error());
$row_rs_rev = mysql_fetch_assoc($rs_rev);
$totalRows_rs_rev = mysql_num_rows($rs_rev);
 
function ID() {
      srand(time());
      $a="0123456789";
         for($i; $i<=16; $i++) {
              $id.=substr($a, (rand()%(strlen($a))),1);
         }
       return(md5($id));
 }
if (!empty($id)) {
    echo "ID : $id<br>\n";
}
 
$id=ID();
$_SESSION['id_defeito'] = $id;
 
 
 
 
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "[url=http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd]http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd [/url]">
<html xmlns="[url=http://www.w3.org/1999/xhtml]http://www.w3.org/1999/xhtml [/url]" lang="pt">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Loja iHouse - Abertura de Ordem de Serviços</title>
<link href="css/loja.css" rel="stylesheet" type="text/css" />
<style type="text/css">
#geral #topo #lj ul li #abOS{font-weight:bold; color:#0099FF;}
#geral #products div #meucadastro p { float: left; height: 30px; width: 100%; margin-bottom: 5px; }
#geral #products div h1 {color: #45637A; font: bold 20px Arial,Helvetica,sans-serif; margin: 0 0 11px; padding: 0; text-transform: none;}
#geral #products div #meucadastro p input{padding:5px; background:#EFEEEE; border:none; margin:0 25px;}
#geral #menuprods ul li #mnuos1 {font-weight:bold; color:#45637A;}
#geral #products form p #observacoes { border: 1px solid #517087; padding:5px; width:848px;}
#geral #products form #gerar {font-family: Arial, Helvetica, sans-serif; color: #FFF; background: #45637A; padding: 7px 10px; font-weight: bold; border-style: none; cursor:pointer; margin-left:12px;}
#geral #products #os {padding-left:12px;}
#geral #products #os p {margin-left:13px;}
</style>
<link rel="SHORTCUT ICON" href="[url=http://www.ihouse.com.br/images/favicon.ico]http://www.ihouse.com.br/images/favicon.ico [/url]" />
<script type="text/javascript">
<!--
function MM_popupMsg(msg) { //v1.0
  alert(msg);
}
//-->
</script>
 
<script type="text/javascript">
 
iframe = document.getElementById("list").contentWindow;
iframe.MM_validateForm();
 
</script>
 
</head>
<body>
<div id="geral">
  <?php include('lj.php') ?>
  <div id="menuprods">
  <ul>
  <li><a href="abertura-ordem-de-servicos.php" title="Nova O.S." id="mnuos1">NOVA O.S.</a></li>
    <!--<li><a href="historico-de-os.php" title="Histórico de O.S." id="mnuos2" style="background:none;">Histórico de O.S.</a></li>-->
      <li><a href="historico-de-os.php" title="Histórico de O.S." id="mnuos2" style="background:none;">Histórico de O.S.</a></li>
  </ul>
  </div>
  <div id="products" style="margin-top:0;">
  <form action="<?php echo $editFormAction; ?>" method="POST" name="os" id="os">
        <h1 class="titles">Dados da Revenda</h1>  
        <input name="data" type="hidden" value="<?php echo date('d/m/Y'); ?>" />
        <input name="mes" type="hidden" value="<?php echo date ('m'); ?>" />
        <input name="ano" type="hidden" value="<?php echo date ('Y');?>" />
        <input name="revenda" type="hidden" value="<?php echo $_SESSION['kt_login_id']; ?>" />
        <input name="usuario" type="hidden" value="<?php echo $_SESSION['revenda']; ?>" />
        <input name="defeito" type="hidden" value="<?php echo $_SESSION['id_defeito']; ?>" />
    <p>
        <strong>Data</strong>: <?php echo date ('d/m/Y'); ?><br />
        <strong>Usuário</strong>: <?php echo $_SESSION['kt_login_user']; ?><br />
        <strong>Revenda</strong>: <?php echo $row_rs_rev['revendedores_empresa']; ?><br />
        <strong>CNPJ</strong>:<?php echo $row_rs_rev['revendedores_cnpj']; ?> <br />        
        <strong>Inscrição Estadual</strong>: <?php echo $row_rs_rev['revendedores_inscricao_estadual']; ?><br />
        <strong>Endereço</strong>: <?php echo $row_rs_rev['revendedores_endereco']; ?> - <?php echo $row_rs_rev['revendedores_bairro']; ?> - <?php echo $row_rs_rev['revendedores_cep']; ?> - <?php echo $row_rs_rev['revendedores_cidades']; ?> - <?php echo $row_rs_rev['revendedores_uf']; ?>
    </p>
    <hr />
    <h1 class="titles">Adicionar Produtos</h1>        
<iframe name="list" id="list" src="lista-de-produtos.php" width="923" height="455" frameborder="0" scrolling="no"></iframe>
    <p style="margin-top:10px;"><label><strong>Observações</strong></label><br /><textarea name="observacoes" cols="5" rows="10" id="observacoes" style="font-family:Arial, Helvetica, sans-serif;"></textarea></p>
    <input name="enviar" type="submit" id="gerar" onclick="window.document.getElementById('list').MM_validateForm();MM_popupMsg('O.S. gerada com sucesso !\r')" value="GERAR O.S." />
    <input type="hidden" name="MM_insert" value="os" />    
  </form>
  </div>
  <?php include('rodape.php')?>
</div>
</body>
</html>
<?php mysql_free_result($rs_rev); ?>
 

Quando eu clicar no botão gerar quero que ele pegue a validação do iframe.

Compartilhar este post


Link para o post
Compartilhar em outros sites

×

Informação importante

Ao usar o fórum, você concorda com nossos Termos e condições.