I am trying to teach myself javascript through simple programming ideas. I tasked myself to make a way to calculate two numbers and provide a total of the results by option of using any of the four available operators. It's sort of a very simple calculator, to get to the point. I don't think I need to copy my html code - so I just posted my javascript.
Since I am new to programming in general and javascript, I looked around the web and found some code pointers.
<script>
function add() {
var entry1 = document.getElementById("entry1").value;
var entry2 = document.getElementById("entry2").value;
var sum = Number(entry1)+Number(entry2);
document.getElementById("results").value=sum
}
function sub() {
var entry1 = document.form.entry1.value;
var entry2 = document.form.entry2.value;
var sum = Number(entry1)-Number(entry2);
document.form.results.value=sum
}
function multi() {
var entry1 = document.form.entry1.value;
var entry2 = document.form.entry2.value;
var sum = Number(entry1)*Number(entry2);
document.getElementById("results").value=sum
}
function div() {
var entry1 = document.form.entry1.value;
var entry2 = document.form.entry2.value;
var sum = Number(entry1)/Number(entry2);
document.getElementById("results").value=sum
}
</script>
I think this gives you insight into what I am playing around with. I thought it was interesting I found a way to get around using document.getElementByID
, but I guess what I am trying to understand is how you can using both ways...the document.form...
and document.getElementById
.
Using "document.getElementById" will search the whole DOM looking for "entry1." "Form" in "document.form" refers to the form that encapsulates the whole contents in the <body>
tag. As a theory, I did a <div name="blah">
tag in front of <form name="form">
to see if it would use "blah" if I changed document.form
to document.blah
...it broke. Same thing happened when I tried document.blah.form.entry1
....). I think you can see what I am getting at.
I am just curious as to why document.form.entry1.value;
works like document.getElementById("entry1").value;
?