0

Why does my code under JavaScript won't work if I try to write it under HTML?

<html> <head> <title>Form</title> </head> <body> <form onsubmit="return validate()" method="post"> Number: <input type="text" name="num1" id="num1" /><br /> Repeat: <input type="text" name="num2" id="num2" /><br /> <input type="submit" value="Submit" /> </form> <script> function validate() { var n1= document.getElementById("num1"); var n2= document.getElementById("num2"); if (n1.value!="" && n2.value!="") { if (n1.value == n2.value) { return true; } } alert("The values must be equal and not blank); return false; } </script> </body> </html> That's how I did it. I added the script tag under the body, and that's where I wrote my code for JavaScript. It works in the Code Playground, but when I tried to do it on my notepad it doesn't work :<

1st Nov 2019, 6:33 AM
Eline Linlin
Eline Linlin - avatar
4 Answers
+ 3
This is html code. It will not work on notepad. You have to save it with .html extension file then open it on browser. It will work.
1st Nov 2019, 7:57 AM
A͢J
A͢J - avatar
+ 1
As you added in this code or you can create seperate js file and include it in html.
1st Nov 2019, 8:16 AM
A͢J
A͢J - avatar
+ 1
in form, onsubmit, don't return validate(), just validate() <form onsubmit="validate()"> After pasting in notepad, choose Save As, choose file type All Files, name file index.html with file extension html. Now in your desktop or folder, you see a HTML file which will be opened by browser.
1st Nov 2019, 2:09 PM
Gordon
Gordon - avatar
0
A J Ohhh I see thanks for that... how will I add my JavaScript code to it though? I really need to add it in order to work.
1st Nov 2019, 8:07 AM
Eline Linlin
Eline Linlin - avatar