So I’m about 10 hours into my programming career; bear with me please.
My attempt to solve the problem of creating a website with an HTML input area and button such that entering a number between 0 and 100 inclusive and clicking the button will take your score and return an alert box with whatever letter grade corresponds to that score is as follows:
First, the .js file
function grade() {
score = document.form1.grade.value;
if (score==100) {alert("Perfect score!");}
else if (score>=90) {alert("You got an A");}
else if (score>=80) {alert("You got a B");}
else if (score>=70) {alert("You got a C");}
else if (score>=60) {alert("You got a D");}
else {alert("Failure.");}
}
And the HTML:
<form name="form1" onsubmit="return false">
<input type="number"
name="grade"
value=""
min="0" max="100">
</form>
<input type="button" value="Grade" onclick="grade()">
I understand that this is at the level of being trivial, but just doing this simple exercise raised a ton of questions for me.
- Why does the button not work if I put it within the form tags?
- I tried for an unreasonably long time to get the js to work with
switch. Is there a way to do it or am I doing it right with severalif/else ifstatements? - When I didn’t have
onsubmit="return false"pressing enter in the text field basically borked everything, and `onsubmit=”grade()” didn’t work at all. Is there any way to make it so that when you enter a number (87) and press return it doesn’t submit but executes the grade() function? - Any general structural improvements?
gradeis set to yourinputelement, which is also namedgrade.ifstatements should be fine here.window.grade(); return false;. Thewindow.gradegets around the fact that plaingradeis masked to theinput.addEventListener. This lets you completely remove the snippets of JavaScript code (eg.onclick="window.grade(); return false;") from the HTML, leading the HTML to be cleaner. You also may want to learn aboutdocument.getElementById(which you’d use to replacedocument.form1.grade, which is a slightly old way of doing things).Here’s an example using
addEventListenerandgetElementById. Have fun learning to program!