Use of quotations in getElementById

Use of quotations in getElementById
0.0 0

#1

Hi everyone,

I am on chapter 49 of “A Smarter Way To Learn Javascript”. The problem is the use of quotations in getElementById().

When I use the quotations as the book says I pass the exercise, but when I use the same code in CodePen or in VScode it does not work.

The only difference is in line 7 (I will write the whole code later):

document.getElementById(field)
//works
VS
document.getElementById("field")
//does not work

Here is the entire code that works:

1-<form onSubmit="checkEmail('email');">
2-  <input type="text" id="email">
3-  <input type="submit" value="Submit">
4-</form>
5-<script>
6-    function checkEmail(field) {
7-      var val = document.getElementById(field).value;
8-      if (val === "") {
9-      alert("Please, enter your email address");
10-      }
11-  }
12-   </script>

This code does not work:

1-<form onSubmit="checkEmail('email');">
2-  <input type="text" id="email">
3-  <input type="submit" value="Submit">
4-</form>
5-<script>
6-    function checkEmail(field) {
7-      var val = document.getElementById("field").value;
8-      if (val === "") {
9-      alert("Please, enter your email address");
10-      }
11-  }
12-   </script>

When I check documentations like MDN I see that they use quotations. What am I missing?

Thanks.


#2

You’re not using your field parameter anywhere.The field parameter contains the name of the id.
What you’re doing in the line 7 is storing a DOM object with an id=“field” which I pressume doesn’t exist.

Take this code for example:

var myString="I'm a string";

//this is what you're doing
console.log("myString");

//this is the correct way
console.log(myString);

Hopefully you’re going to understand what I meant,and resolve your problem!