-1
<!DOCTYPE html>

<html>
  <head>
        <title>Greet</title>
  </head>
  <body>
        <form id="demo">
              <input id="name" placeholder="Name" type="text"/>
              <input type="submit"/>
        </form>
        <script>
              function greet()
              {
                    alert('hello, ' + document.getElementById('name').value);
              }
              document.getElementById('demo').onsubmit = greet();
        </script>
  </body>

The alert does not show the name I submitted. Only hello,. But if I rewrite code like this document.getElementById('demo').onsubmit = greet; then it works. But why? And this works as well:

<!DOCTYPE html>

<html>
  <head>
        <title>dom0</title>
  </head>
  <body>
        <form id="demo" onsubmit="greet()">
              <input id="name" placeholder="Name" type="text"/>
              <input type="submit"/>
        </form>
        <script>
              function greet()
              {
                    alert('hello, ' + document.getElementById('name').value);
              }

        </script>
  </body>

juanli
  • 583
  • 2
  • 7
  • 19

1 Answers1

1

The reason it works is because greet refers to the function itself. When you write greet() you are passing the output of the greet function because the parenthesis call the function and return the output.

Lilith
  • 437
  • 2
  • 11
  • Sorry, I know what you're saying. But I still don't understand how it works? why greet() does not give the submitted value? form--> onsubmit--> call greet function, correct? I have Python background. But I don't understand how the function call in javascript works? – juanli Nov 12 '17 at 07:36
  • 1
    Because it is called immediately when you are assigning the value to the onsubmit. Therefore the value is empty. If you pass the function instead it will be called when you submit the form and will therefore (if you inputted one) have a value. – Lilith Nov 12 '17 at 07:39
  • I am lost at this moment. So confusing about the function call in JavaScript. I need to take a rest to think about it. Thanks. – juanli Nov 12 '17 at 07:51