Very simple javascript does not work at all

My javascript in the .php file (static website) is not working. I use 3 other scripts there, and they work, but not this one.

The situation is simple.

javascript is ...

var myFile = document.getElementById('myFile'); myFile.addEventListener('change', function() { alert(this.files[0].size); }); 

and HTML in a PHP file (split)

 <form onsubmit="return anotherfunction();" action="sendForm.php" enctype="multipart/form-data" method="post"> <table> <tr> <td>Attach an image:</td> <td> <input type="file" name="priloha[]" accept="image/*" /></td> </tr> </table> </form> 

And javascript does nothing, it acts as if it does not exist. I tried to use JS in the header, under the header, in the body, in TD input ... I also tried to use it in an external .js file, nothing works at all. I tried changing "change" to "click", none worked. I tried to do this all day and I can’t understand what happened.

So, I tried to make much simpler code to check what was wrong, and it looked like “change” or “onchange” - the second line of JS does not work.

I also tried to specify the HTML type of the document, did nothing.

My extra .html file, to try even simpler code, looks like this and of course does not work ...

 <!DOCTYPE html> <html> <head> </head> <body> <table> <tr> <td>Input field for click popup:</td> <td> <script type="text/javascript"> var input = document.getElementById('input'); input.addEventListener('click', function() { alert("Hello"); }); </script> <input type="text" id="input" /> </td> </tr> <table> </body> </html> 

Help me, I really don’t know what it is ... I forgot to mention, I tried different browsers - Opera 12.15, the latest FF and Chrome, in no case did not work. But he works in the violin ... thanks for any help in advance

+6
source share
2 answers

Place the script right at the end of the body, right before the </body> .

Scripts are loaded synchronously where they are located, so any script placed before the element in question will not know about the existence of the element.

Besides what Igor said.

+8
source

You do not have a DOM element with id "myFile" in the html that you have included.

+2
source

Source: https://habr.com/ru/post/946541/


All Articles