Ir para conteúdo

POWERED BY:

Arquivado

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

portaWix

funções javascript

Recommended Posts

Pessoal no código abaixo, dentro do script apos o conteudo dentro de window.onload, fora dele vocês podem

observar a funçaõ showHide (el, mode), ela dispara um evento no formulário de modo que se uma das condições

dentro dos if's dentro de window.onload não for obedecida uma mensagem de erro temporizada e ativada, mostrada

por 2 segundos e depois desaparece. Gostaria de saber por que se essa mesma funçao for declarada dentro de window.onload

antes de ser usada nos if, isso gera um BUG no qual ela não temporiza da forma correta (testei pra varios valores de segundos),

e a mesma so funciona se for omitido o return false depois do if.

ps: O CODIO DO JEITO QUE ESTA, FUNCIONA, DESDE QUE A FUNCAO showHide() esteja FORA DE window.onload, porem quando declarada dentro GERA O BUG

 

 

 

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR...nsitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>Exercicio 05</title>
        <link href='http://fonts.googlea...reek,vietnamese' rel='stylesheet' type='text/css'>
        <script type="text/javascript">
            window.onload = function () {


                var form = document.getElementById("form");
                var nome = document.getElementById("name");
                var phone = document.getElementById("phone");
                var mail = document.getElementById("mail");
                var login = document.getElementById("login");
                var pass = document.getElementById("password");
                var send = document.getElementById("submit");


                var validaEmail = /^\w+@\w+\.com$/igm;
                var validaLogin = /^(\w|\d)+$/igm;




                var allInputs = document.getElementsByTagName("input");


                for (var i = 0; i < allInputs.length; i++) {
                    allInputs[i].size = 40;
                }


                function insertMessage (idElement, message) {
                    var element = document.getElementById(idElement);
                    element.innerHTML = message;


                }


                send.onclick = function () {


                    if (nome.value == "" || mail.value == "" || login.value == "" || pass.value == "") {
                        insertMessage('error', 'Preencha todos os campos obrigatórios!');
                        showHide('error', 'block');


                    } else if (validaEmail.test(mail.value) == false){
                        insertMessage('error', 'Email no formato incorreto!');
                        showHide('error', 'block');


                    } else if ((login.value.length > 12 ||login.value.length < 6) && validaLogin.test(login.value)){
                        insertMessage('error', 'Login deve ter entre 4 a 12 caracteres e não pode usar caracteres especiais!');
                        showHide('error', 'block');


                    } else {
                        showHide('error', 'none');
                        form.submit();
                    }
                    return false;
                }
            }


            function showHide (el, mode) {
                document.getElementById(el).style.display = mode;
                setTimeout("showHide('error', 'none')", 2000);
            }
        </script>
        <style type="text/css">
            * {
                margin: 0px;
                padding: 0px;
                list-style: none;
                outline: none;
            }


            form {
                width: 400px;
                height: 500px;
                border: 2px solid #000000;
                border-radius: 30px;
                margin: 50px auto;
            }


            label {
                display: block;
                margin-left: 70px;
                margin-top: 40px;
                font-family: 'Roboto Condensed', sans-serif;
            }


            input {
                margin-left: 70px;
                margin-bottom: 30px;
                font-family: 'Roboto Condensed', sans-serif;
                display: block;
            }


            #error {
                width: 400px;
                height: 40px;
                border: 2px solid #000000;
                border-radius: 30px;
                margin: 10px auto;
                background-color: #d6a95f;
                text-align: center;
                text-transform: uppercase;
                line-height: 40px;
                font-size: 15px;
                font-family: 'Roboto Condensed', sans-serif;
                display: none;
            }
        </style>
    </head>


    <body>
        <div id="error"></div>
        <form action="" method="get" id="form">
            <label for="name">Nome* : </label>
            <input type="text" name="nome" id="name"/>


            <label for="phone">Telefone : </label>
            <input type="text" name="telefone" id="phone"/>


            <label for="mail">E-mail* : </label>
            <input type="text" name="email" id="mail"/>


            <label for="login">Login* : </label>
            <input type="text" name="login" id="login"/>


            <label for="password">Senha* : </label>
            <input type="password" name="senha" id="password"/>


            <input type="submit" name="enviar" id="submit"/>
        </form>
    </body>
</html>

Compartilhar este post


Link para o post
Compartilhar em outros sites

O bug é que sé a função for declarada dentro de window.onload, ela não temporiza da forma correta. E so passa a funcionar se removido o return false dentro do evento onclick do botao

Compartilhar este post


Link para o post
Compartilhar em outros sites

Não faz sentido nenhum cara.

 

Mas eu vejo um erro: vc está utilizando .click() para formulários.

O correto é vc utilizar .submit() no form, e nunca no botão submit.

 

Em vez de fazer isso:

send.onclick = function () {
O correto é:

form.addEventListener('submit', function() {
O que vc chama de "não temporizar direito" ? seria um reload na pagina, q faz o erro sumir?

Compartilhar este post


Link para o post
Compartilhar em outros sites

O código do jeito que esta funciona corretamente, a minha duvida é observe que tem-se o código

 

<script type="text/javascript">

window.onload = function () {

 

.. monte de codigo aqui

 

}

 

function showHide (el, mode) {

document.getElementById(el).style.display = mode;

setTimeout("showHide('error', 'none')", 2000); ---> TEMPORIZADA PRA FAZER O AVISO SUMIR EM 2 SEGUNDOS

}

</script>

 

DESSE JEITO ACIMA FUNCINA CORRETAMENTE E O AVISO FUNCIONA NO TEMPO CORRETO POREM SE TIVER DESSE JEITO

 

<script type="text/javascript">

window.onload = function () {

 

.. monte de codigo aqui

 

function showHide (el, mode) {

document.getElementById(el).style.display = mode;

setTimeout("showHide('error', 'none')", 2000); ---> TEMPORIZADA PRA FAZER O AVISO SUMIR EM 2 SEGUNDOS

}

 

}

 

</script>

 

A FUNCAO showHide DECLARADA dentor de onload, nao passa mais a temporizar no tempo de 2 segundos

na verdade nao passa a temporizar de jeito correto nenhum, fica um negocio bem instantâneo, ah e isso só

funciona se vc tirar o return false apos o if, caso contrario o aviso de erro nem some

Compartilhar este post


Link para o post
Compartilhar em outros sites

Sim, o problema do return false ali, é como eu disse vc usar click() no lugar de submit() q é o correto.

 

Esse "instantâneo" é pq provavelmente o js quebrou, e não está na verdade fazendo nada.

Aparece algo no console de erros ?

 

Ctrl + Shift + J no Chrome ou Firefox.

Compartilhar este post


Link para o post
Compartilhar em outros sites

Tipo com o return false nem sumir mais o erro some, se você tira o return false ai fica instatâneo

o erro que aparece é :

 

Failed to load resource: net::ERR_NAME_NOT_RESOLVED

Compartilhar este post


Link para o post
Compartilhar em outros sites

O "problema" provavelmente era escopo. O que você cria dentro de window.onload = () {} pertence ao escopo dessa função.

 

Quando você coloca showHide() dentro de window.load e chama o setTimeout(), ele procura no escopo global (window), e não encontra, ai aparece o erro.

 

Como a recursão de showHide chamar showHide é bastante esquisita, eu remodelei a forma de uso e reescrevi para utilizar o evento onsubmit. Veja como ficou:

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR...nsitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>Exercicio 05</title>
        <link href='http://fonts.googlea...reek,vietnamese' rel='stylesheet' type='text/css'>
        <script type="text/javascript">
            window.onload = function () {

                var form = document.getElementById("form"),
                    nome = document.getElementById("name"),
                    phone = document.getElementById("phone"),
                    mail = document.getElementById("mail"),
                    login = document.getElementById("login"),
                    pass = document.getElementById("password"),
                    error = document.getElementById("error"),
                    send = document.getElementById("submit");

                var validaEmail = /^\w+@\w+\.com$/igm;
                var validaLogin = /^(\w|\d)+$/igm;


                var allInputs = document.getElementsByTagName("input");

                for (var i = 0; i < allInputs.length; i++) {
                    allInputs[i].size = 40;
                }

                form.addEventListener('submit', function (event) {
                    if (nome.value == "" || mail.value == "" || login.value == "" || pass.value == "") {
                        insertMessage(error, 'Preencha todos os campos obrigatórios!');
                        event.preventDefault();

                    } else if (validaEmail.test(mail.value) == false){
                        insertMessage(error, 'Email no formato incorreto!');
                        event.preventDefault();

                    } else if ((login.value.length > 12 ||login.value.length < 6) && validaLogin.test(login.value)){
                        insertMessage(error, 'Login deve ter entre 4 a 12 caracteres e não pode usar caracteres especiais!');
                        event.preventDefault();

                    } else {
                        removeMessage(error);
                        form.submit();
                    }
                });
            };

            function removeMessage (element) {
                setTimeout(function(){
                  element.style.display = 'none';
                }, 2000);
            }
            function insertMessage (element, message) {
                element.innerHTML = message;
                element.style.display = 'block';
                removeMessage(element);
            }
        </script>
        <style type="text/css">
            * {
                margin: 0px;
                padding: 0px;
                list-style: none;
                outline: none;
            }

            form {
                width: 400px;
                height: 500px;
                border: 2px solid #000000;
                border-radius: 30px;
                margin: 50px auto;
            }

            label {
                display: block;
                margin-left: 70px;
                margin-top: 40px;
                font-family: 'Roboto Condensed', sans-serif;
            }

            input {
                margin-left: 70px;
                margin-bottom: 30px;
                font-family: 'Roboto Condensed', sans-serif;
                display: block;
            }

            #error {
                width: 400px;
                height: 40px;
                border: 2px solid #000000;
                border-radius: 30px;
                margin: 10px auto;
                background-color: #d6a95f;
                text-align: center;
                text-transform: uppercase;
                line-height: 40px;
                font-size: 15px;
                font-family: 'Roboto Condensed', sans-serif;
                display: none;
            }
        </style>
    </head>

    <body>
        <div id="error"></div>
        <form action="" method="get" id="form">
            <label for="name">Nome* : </label>
            <input type="text" name="nome" id="name"/>

            <label for="phone">Telefone : </label>
            <input type="text" name="telefone" id="phone"/>

            <label for="mail">E-mail* : </label>
            <input type="text" name="email" id="mail"/>

            <label for="login">Login* : </label>
            <input type="text" name="login" id="login"/>

            <label for="password">Senha* : </label>
            <input type="password" name="senha" id="password"/>

            <input type="submit" name="enviar" id="submit"/>
        </form>
    </body>
</html>
Ainda poderíamos melhorar o window.onload, mas vamos uma coisa de cada vez.

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.