本記事では よくあるミスについて検討します。
以前利用した[ form-02.html ] と蛍光色の箇所が異なっています。
一部異なるだけで、どれくらい結果が変わるかを理解しておきましょう。
以下では [ form-04.html ]を使うことにします。
[ form-04.html ]
<html>
<head>
<title>JavaScript form 04</title>
<body>
<p>
<label>入力値1<input type=”text” id=”input1″></label><br>
<label>入力値2<input type=”text” id=”input2″></label><br>
<input type=”button” value=”関数実行” id=”set”>
</p>
<script>
document.getElementById(“set”).onclick = function() {
const input1 = document.getElementById(“input1”).value;
const input2 = document.getElementById(“input2”).value;
let plus = input1+ input2;
document.write(“足し算 = ” + plus);
};
</script>
<body>
</html>

とウェブサイト上に表示されていると思います。
このサイト上の 入力値1 に 半角数字で 5 と入力して
このサイト上の 入力値2 に 半角数字で 8 と入力して 関数実行をクリックすると
足し算 = 58 とウェブサイト上の表示が変更されましたね。
このようなアクションが実現された理由を説明していきます。
<p>
<label>入力値1<input type=”text” id=”input1″></label><br>
<label>入力値2<input type=”text” id=”input2″></label><br>
<input type=”button” value=”関数実行” id=”set”>
</p>
の部分で テキストボックスに ninput1 と input2 という id をそれぞれ割り振っています。
ウェブサイトでは、タグに id プロパティ や name プロパティを付与することができます。
id や name をそれぞれ重複しないように付与することで、
特定の id や name に対して○○しなさい という命令ができます。
上記の html では button に対しても set という id を割り振っていますね。
<script> タグ内では その set を利用して 処理を進めています。
<script>
document.getElementById(“set”).onclick = function() {
const input1 = document.getElementById(“input1”).value;
const input2 = document.getElementById(“input2”).value;
let plus = input1 + input2
document.write(“足し算 = ” + plus);
};
</script>
document.getElementById(“set“).onclick とは、
id が set の箇所が クリックされた ということを意味します。
const input1 = document.getElementById(“input1“).value; は
ウェブサイトのidの input1 の値を、
JavaScript の 定数 input1 に格納する という意味です。
ウェブサイトのid と JavaScript で同じ名前を使う理由は、対象を間違えにくくするためです。
(同じ名前を使う義務はありませんので、異なる名前を使ってももちろん構いません。)
const input2 = document.getElementById(“input2“).value; は
ウェブサイトのidの input2 の値を、
JavaScript の 定数 input2 に格納する という意味です。
document.getElementById(“set”).onclick = function() {
const input1 = document.getElementById(“input1”).value;
const input2 = document.getElementById(“input2”).value;
let plus = input1 + input2
document.write(“足し算 = ” + plus);
}
は id が set の箇所が クリックされたら
{ } 内に記載された内容を実行しなさい
ということを意味します。
そして
document.write(“足し算 = “ + plus); は、
画面上に 足し算 = という文字列 と plus の変数値 を表示させなさい
という意味です。
= function(){
} は、自分で作成した 関数 になります。
プログラムで言う関数は、数学で習った関数という意味ではなく、
一連の処理のことです。
関数に名前を使うことで、簡単に使いまわしができるようになります。
let plus = input1 + input2 とは
input1という文字列 と input2という文字列 をつないだものを plus に格納する
という意味です。
つまり
5 という文字 と 8 という文字 をつないだ結果
plust = 58 となってしまうのです。