I have some javacript that I am trying to implement on an HTML page. The code is below – how can I get it to run as soon as the .html file is opened? It want it to prompt me to enter the weight as soon as i open it.
<script type="text/javascript">
var weight = parseInt(prompt("What is your weight?"));
if (weight > 126) {
alert('Please enter a weight lighter than 126');
}
document.writeln('<br/>');
var wArray = ["fly", "superfly", "bantam", "superbantam", "feather"];
function recruit() {
if (0 < weight < 112){
document.writeln('You are in' + wArray[0] +'class!');
}
if (112 < weight < 115){
alert('You are in' + wArray[1] +'class!');
}
if (weight > 115 && weight < 118){
alert('You are in' + wArray[2] +'class!');
}
if(weight > 118 && weight < 122){
alert('You are in' + wArray[3] +'class!');
}
if (weight > 122&& weight < 126){
alert('Your weight class is' + wArray[4]);
}
</script>
You have 2 problems with the script:
recruit()is missing closing bracket}recruit()anywhere.Several other issues 🙂 :
112 < weight < 115is not what you want. It will return true even when weight is 1000. It will check if weight is bigger than 112 and then compare if the result is smaller than 115.Try:
You left some values in your checks. If you check for
weight < 118in oneifandweight > 118in anotherifthen what will happen if weight is exactly 118?Use
if { } else if { }blocks instead of multiple if-s. In your recruit function even when the weight is 110 and the body of 1stifblock is executed, you are still checking the weight in every otherif.Add spaces to the output strings, e.g.:
'You are in ' + wArray[0] + ' class!:).As Rocket wrote in the comments:
parseInt()should be called with10as a 2nd parameter (radix) to force parsing into decimal system. See this.Bonus: Stop using
document.writelnas soon as possible as it is teaching you bad practices. For example see this or this.HERE is a version addressing these issues.
Note: The code is executed inside
window.onloadto make sure that the rest of the document is already loaded so he can access thediv.