The HTML page is not "calling" Javascript

Asked

Viewed 25,329 times

0

I have the following problem, I am using Notepad++ as editor, and when I load the HTML page and fill in the CPF data, nothing happens, there is no answer.

My HTML page is:

 <html>
   <head>
      <script type="text/javascript" src="js/aula09.js"></script>
    </head>
       <body>
      <form id="formulario">
        <fieldset>
        <legend>Validação e Formatação</legend>
        <label for="cpf">CPF:<label>
        <input name="cpf" type="text" />

        <label for="email">Email:<label>
        <input name="email" type="text" />

        <a href="#" onclick="validar()">Validar</a>
        </fieldset>
  </form></body></html>

My Javascript file is:

 function validar(){
    var formulario = document.getElementById("formulario");
    var cpf = formulario.cpf;
    var email = formulario.email;
    var re_cpf = /^([\d]{3})([\d]{3})([\d]{3})([\d]{2})$/;
    var re_email = /^([\w-]+(\.[\w-]+)*@(([\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(\.[a-z]{2})?)$/i;   

    if(re_cpf.test(cpf.value)){
        alert("CPF válido");}
        else{
            alert("CPF inválido");
    }
}

What could be the problem?

  • Can you display the full <form> html? Your JS uses some information you haven’t shown in HTML

  • 1

    Has a } the most at the end of the code. Check your indentation and check what appears in the browser console when using the page.

  • I don’t know why the full form didn’t appear. I’ll try again below:

  • <form id="formulary"> <fieldset> <Legend>Validation and Formatting</Legend> <label for="Cpf">CPF:<label> <input name="Cpf" type="text" /> <label for="email">Email:<label> <input name="email" type="text" /> <a href="#" onclick="validate()">Validate</a> </fieldset> </form>

  • rafaels88, there really is an extra "}", but even correcting this error the function remains unanswered. Thank you anyway.

  • @sscarvalho, the error is in re_email, remove it will work

  • @sscarvalho If you have had any success, collaborate with Sopt and mark an answer as correct or post your solution.

  • window.onload = Function() { Document.getElementById ... }, you can only use getElementById after rendering the element with ID

Show 3 more comments

2 answers

6


Your problem:

and when I load the HTML page and fill in the CPF data, nothing happens, there is no answer.

Instead of function validar () {, use another scope format. In this case, validar = function () { // ... }. Behold:

validar = function () {
    var formulario = document.getElementById("formulario");
    var cpf = formulario.cpf;
    var email = formulario.email;
    var re_cpf = /^([\d]{3})([\d]{3})([\d]{3})([\d]{2})$/;
    var re_email = /^([\w-]+(\.[\w-]+)*@(([\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(\.[a-z]{2})?)$/i;   

    if(re_cpf.test(cpf.value)){
        alert("CPF válido");}
        else{
            alert("CPF inválido");
    }
}

Example running on jsFiddle.


Still, your next mistake is a problem with regular expression. I solved it for you:

validar = function () {
    var formulario = document.getElementById("formulario");
    var cpf = formulario.cpf;
    var email = formulario.email;
    var re_cpf = /^([\d]{3})([\d]{3})([\d]{3})([\d]{2})$/;
    var re_email = /^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$/;   

    if(re_cpf.test(cpf.value)){
        alert("CPF válido");}
        else{
            alert("CPF inválido");
    }

    if(re_email.test(email.value)) alert('E-mail válido');
    else alert('E-mail inválido');
}

Example running on jsFiddle (updated)


Why does your coupler onclick is not cocking validar()?

Based on a questionnaire made via a comment of the OP - very good by the way! - I will answer this question with minimalism:

function x () { 
  // do something
};

The above format is called a "function statement", which in turn is a template where the function is saved to be, say, used "later" - not in the first instance. As you can see, no variable is signed to it.

Next, the model proposed by me:

x = function () { 
  // do something
};

It’s called "function expression" in literal translation. It means that you sign to "x" a function to be used at any time when x be executed.

And what’s the practical difference?

In your specific case, you are using the observer onclick "inline"1. His scope is the GIFT and will perform a function that already exists at the moment the customer clicks on the element you designated to trigger the function named by you as validar().

While validar() is a function that "not yet" exists, its effect will not be triggered.

But what do you mean, "It doesn’t exist yet"? It does! I wrote!

There is, but yours <a> does not yet know who he is. If you write this HTML, the function validar() {} will work:

<a href="#" onclick="validar()">Validar que funciona</a>

<script>
    function validar() {
        alert('hello!');
    };
</script>

In your case, you are writing Javascript in an external file (js/aula09.js) and therefore he had not yet been declared for the GIFT.

I still don’t understand

If you declare a function as previously explained in the same file you call it in, everything will work as expected. As long as you do not do this, the functions should be expressed - explained to the DOM who is who.

To illustrate, take a look in this jsFiddle. The Javascript that is at the bottom left will not work while what is embedded in your HTML will execute your role - this is because the Javascript of this bottom white square is "external" to HTML.

For comparison purposes, if you put in a file .js external this content:

f = function () {
  alert('Olá!');
};

And put in a file .html this:

<a href="#" onclick="x()">Funciona!</a>
<a href="#" onclick="f()">Também funciona!</a>

<script>
    function x() {
        alert('hello!');
    };
</script>

You’ll realize that both will work, just like in this other jsFiddle.


1: In this case, "inline" means that you are using Javascript via HTML in the line of your element - it is not an effect unobtrusive.

  • Thank you very much, William Oderdenge, it’s worked now. However, as I would like not only to make it work, but above all to understand what I am doing, I would also like you to clarify the following question. I’m doing an exercise where the author uses "Function validate () {" instead of "validate = Function() {". In the video it shows that it works the same way. Why with me is only working the scope format you suggested?

  • @sscarvalho Beautiful question! I made sure to reformulate my answer to better clarify you. I hope now it is clear!

  • The validarQueNaoFunciona works yes. You’ve fallen into the jsfiddle’s scope trick, which puts scripts into an onload function by default, removing them from the global scope. Your explanation about function x vs x = function is incorrect, in fact it is the opposite: function x(){} suffers Hoisting and is available from the top of the script, while in x = function occurs Hoisting only of variable declaration, but not of value assignment.

  • No prank, @bfavaretto. You have selected No wrap - in <body> - if you consult the DOM, Javascript will be there, entering exactly the question I raised where the scope is "lost" when Javascript is avowed externally.

  • William, it makes no difference if the file is external or not, nor if it is loaded in the head or the end of the body. http://plnkr.co/edit/IblNhkr7klHNELKD989I?p=preview

  • PS: The downvote is mine, because the answer contains incorrect information that can confuse people (let me know if you want to discuss this, we can chat).

Show 1 more comment

1

I saw here that your code has a problem with the regular expression that you defined in the variable 're_email'. With that the code is breaking and ends up not running your code.

Also had some tags that were not closed.

I made the corrections here and now it works with the code below. Then take a look only at the expression you created in that variable 're_email', for e-mail validation.

I hope I helped. Hugs.

            <html>
                <head><script>
                     function validar(){
                        var formulario = document.getElementById("formulario");
                        alert(formulario);
                        var cpf = formulario.cpf.value;
                        alert(cpf);
                        var email = formulario.email.value;
                        alert(email);
                        var re_cpf = /^([\d]{3})([\d]{3})([\d]{3})([\d]{2})$/;

                        if(re_cpf.test(cpf)){
                        alert("CPF válido");
                        } else {
                        alert("CPF inválido");
                        }
                    }
                </script></head>
                <body>
                    <form id="formulario">
                        <fieldset>
                        <legend>Validação e Formatação</legend>
                        <label for="cpf">CPF:</label>
                        <input name="cpf" type="text" />

                        <label for="email">Email:</label>
                        <input name="email" type="text" />

                        <a href="#" onclick="javascript:validar()">Validar</a>
                        </fieldset>
                    </form>
                </body>
            </html>
  • "Invalid regular expression: missing )"

  • Thank you very much, Dias, now it’s working with me too. Only it was using distinct files for HTML and Javascript. And in doing so the problem continues to occur. Below is how I wrote and what I think should work: Javascript: Function validar(){ var formulario = Document.getElementById("formulario"); var Cpf = formulario.cpf.value; var email = formulario.email.value; var re_cpf = / ([ d]{3})([ d]{3})([ d]{3})([ d]{2})$/; if(re_cpf.test(Cpf)){ Alert("valid CPF");} Else{ Alert("invalid CPF"); } }

  • HTML: <html> <head> <script type="text/javascript" src="js/aula09.js"></script> </head> <body> <form id="formulary"> <fieldset> <Legend>Validation and Formatting</Legend> <label for="Cpf">CPF:</label>input <name="Cpf" type="text" /> <label for="email">Email:</label> <input name="email" type="text" /> <a href="#" onclick="validate()">Validate</a> </fieldset> </form> </body> </html/>

  • I edited my question.

  • Change <form id="formulario"> for: <form id="formulario" name="formulario" method="post">, instead of using getElementById, try: document.formulario; to Cpf: document.formulario.cpf. You are taking an attribute from the form document, not from the gift of the rendered object... Getelementbyid does not consider the gift object, but the rendered element in your view, which has no attributes of type name for example.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.