0

I am currently learning javascript. And I stumbled upon this example code which makes me very confused.

<html>
    <head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>xxxxx</title>
    <script type="text/javascript">
        function a() {
            let x = parseInt(Form1.val1.value);
            let y = parseInt(Form1.val2.value);
            alert("Sum \n" + (x + y));
        }
    </script>
    </head>
  <body text="red">
    <h1> xxxxx </h1>
    
    <form name="Form1">
        <input type="text" name="val1"><br><br>
        <input type="text" name="val2">
        <br><br>
        <input type="button" value="Calul" onclick="a()">

    </form>

  </body>
</html>

Regardless of its content, this is a working code. What I cannot understand is that why using directly Form1 (The "name" of the form) can work here. (However, when I do the same to other element such as <p>, it doesn't work)

I always thought we need to get everything (With pure JS) by using document.getElementByID / ByClass etc. in order to find the element in the HTML to manipulate.

Thanks!

Andres Gardiol
  • 1,312
  • 15
  • 22
Yan Zhuang
  • 436
  • 3
  • 10
  • 5
    That's a long story, mostly about legacy features of DOM, somewhat covered in [this thread](https://stackoverflow.com/questions/3434278/do-dom-tree-elements-with-ids-become-global-variables). In a nutshell, while it's still possible to use this approach, it's better to avoid it. – raina77ow Nov 15 '20 at 00:47

2 Answers2

0

The onclick attribute on an element is a way to bind the click event directly. It will execute whatever is inside the quotes as Javascript (in this case, calling the a() function) when the element is clicked.

It's considered better practice to bind events using the addEventListener method from within Javascript (unless you're using frameworks like React or Angular which have their own ways of doing event binding).

You can read more about DOM onevent handlers here: https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Event_handlers

HaulinOats
  • 3,628
  • 4
  • 21
  • 24
0

Input elements are a special element that has a onclick attribute. It is better to use the addEventListener method to add an click listener to whatever element you want to make clickable.

eg.

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript addEventListener()</h2>

<p>This example uses the addEventListener() method to attach a click event to a paragraph.</p>

<p id="clickableP">CLICKABLE PARAGRAPH ELEMENT</p>



<script>
document.getElementById("clickableP").addEventListener("click", buttonClicked);

function buttonClicked() {
  document.getElementById("demo").innerHTML = "Paragraph was clicked"
}
</script>

</body>
</html> 

More info: https://www.w3schools.com/js/js_htmldom_eventlistener.asp