You are Calling Script Before it's Element Created in DOM Structure.
JavaScript Code:
<script type="text/javascript">
var provinces = ['Gauteng', 'Limpopo', 'Western Cape', 'Northern Cape', 'Mpumalanga', 'Kwazulu Natal', 'North West', 'Eastern Cape', 'Free State'],
select = document.getElementById('provinces');
for (province in provinces) {
select.add(new Option(provinces[province]));
};
</script>
This works perfectly if I place the script in the HTML document (you are placing the script after Select Element Created, That's why it is working)
but nothing happens if I remove the script tags and place it in an external file (You are adding external file in html head section top, the script will be execute instant head section load. It will not wait to load entire body, and thus your script will not get Select Element & you will get JavaScript error in your browser "Uncaught TypeError: Cannot read property 'add' of null at ..."
). I have referenced the js file from within the HTML file with
<script type="text/javascript" src="js/formcalculations.js"></script>
and I have confirmed that I am referencing the correct field.
I'm obviously making some other stupid mistake (You are not stupid, it happens with everyone who are beginners even it happened lots of time with me even... Well, that time I was kid :D). Would any of you experts be kind enough to show me where I am going wrong? (Off course dear, Stackers are everywhere and willing to help each and every person on SO :) :))
The Correct Way is add script or external javascript always at the end of html body, So then your script will get all required elements
from body.
Working Script: Inline (No matter it's before </head>
or before </body>
)
<script type="text/javascript">
window.onload = function() {
var provinces = ['Gauteng', 'Limpopo', 'Western Cape', 'Northern Cape', 'Mpumalanga', 'Kwazulu Natal', 'North West', 'Eastern Cape', 'Free State'],
select = document.getElementById('provinces');
for (province in provinces) {
select.add(new Option(provinces[province]));
};
};
</script>
External Script Code: (No matter it's before </head>
or before </body>
)
window.onload = function() {
var provinces = ['Gauteng', 'Limpopo', 'Western Cape', 'Northern Cape', 'Mpumalanga', 'Kwazulu Natal', 'North West', 'Eastern Cape', 'Free State'],
select = document.getElementById('provinces');
for (province in provinces) {
select.add(new Option(provinces[province]));
};
};
` tag
– Yordan Nikolov Jun 26 '17 at 13:41`. That's a cargo cult performance trick which only applies if you don't want the JS to run until the very last second. (This JS looks like it should run as soon as the select element is available).
– Quentin Jun 26 '17 at 13:42`"
– Quentin Jun 26 '17 at 13:44