はじめに
この記事を読めば、HTMLのonchangeイベントを使いこなせるようになります。
初心者の方にも分かりやすく、onchangeイベントの基本から使い方、応用例までを解説します。
●HTMLのonchangeイベントとは
○onchangeイベントの基本
onchangeイベントは、フォーム要素の値が変更されたときに発生するイベントです。
主にセレクトボックスやチェックボックス、ラジオボタンなどのフォーム要素で使用されます。
●onchangeイベントの使い方
○サンプルコード1:セレクトボックスでの使い方
<select id="selectBox" onchange="showSelectedValue()">
<option value="apple">りんご</option>
<option value="orange">オレンジ</option>
<option value="banana">バナナ</option>
</select>
<script>
function showSelectedValue() {
const selectBox = document.getElementById('selectBox');
const selectedValue = selectBox.value;
alert('選択された果物: ' + selectedValue);
}
</script>
○サンプルコード2:チェックボックスでの使い方
<label>
<input type="checkbox" id="checkBox" onchange="checkChanged()">
チェックボックス
</label>
<script>
function checkChanged() {
const checkBox = document.getElementById('checkBox');
const isChecked = checkBox.checked;
alert('チェック状態: ' + isChecked);
}
</script>
●onchangeイベントの応用例とサンプルコード
○サンプルコード3:フォーム内容の即時表示
<label for="inputText">テキスト入力:</label>
<input type="text" id="inputText" oninput="displayInput()" />
<p>入力内容:<span id="displayText"></span></p>
<script>
function displayInput() {
const inputText = document.getElementById('inputText');
const displayText = document.getElementById('displayText');
displayText.textContent = inputText.value;
}
</script>
○サンプルコード4:条件に応じた表示の切り替え
<select id="selectBox" onchange="displaySection()">
<option value="section1">セクション1</option>
<option value="section2">セクション2</option>
<option value="section3">セクション3</option>
</select>
<div id="section1" class="section">セクション1の内容</div>
<div id="section2" class="section" hidden>セクション2の内容</div>
<div id="section3" class="section" hidden>セクション3の内容</div>
<script>
function displaySection() {
const selectBox = document.getElementById('selectBox');
const selectedValue = selectBox.value;
const sections = document.getElementsByClassName('section');
for (let section of sections) {
section.hidden = section.id !== selectedValue;
}
}
</script>
○サンプルコード5:入力値のバリデーション
<label for="inputNumber">数字入力(1~10):</label>
<input type="number" id="inputNumber" oninput="validateInput()" />
<p id="validationMessage" hidden>数字は1~10の範囲で入力してください。</p>
<script>
function validateInput() {
const inputNumber = document.getElementById('inputNumber');
const validationMessage = document.getElementById('validationMessage');
const inputValue = inputNumber.value;
validationMessage.hidden = inputValue >= 1 && inputValue <= 10;
}
</script>
○サンプルコード6:動的なセレクトボックスの作成
<select id="categorySelect" onchange="updateSubcategory()">
<option value="fruits">果物</option>
<option value="vegetables">野菜</option>
</select>
<select id="subcategorySelect">
</select>
<script>
const categories = {
fruits: ['りんご', 'オレンジ', 'バナナ'],
vegetables: ['トマト', 'キャベツ', 'にんじん']
};
function updateSubcategory() {
const categorySelect = document.getElementById('categorySelect');
const subcategorySelect = document.getElementById('subcategorySelect');
const selectedCategory = categorySelect.value;
subcategorySelect.innerHTML = '';
categories[selectedCategory].forEach(item => {
const option = document.createElement('option');
option.value = item;
option.textContent = item;
subcategorySelect.appendChild(option);
});
}
updateSubcategory();
</script>
○サンプルコード7:オートコンプリート機能の実装
<input type="text" id="searchBox" oninput="autocomplete()" list="suggestions" />
<datalist id="suggestions"></datalist>
<script>
const words = ['りんご', 'バナナ', 'オレンジ', 'キウイ', 'ぶどう'];
function autocomplete() {
const searchBox = document.getElementById('searchBox');
const suggestions = document.getElementById('suggestions');
const inputValue = searchBox.value;
suggestions.innerHTML = '';
words.forEach(word => {
if (word.startsWith(inputValue) && inputValue !== '') {
const option = document.createElement('option');
option.value = word;
suggestions.appendChild(option);
}
});
}
</script>
○サンプルコード8:画像のプレビュー表示
<input type="file" id="imageInput" onchange="previewImage()" accept="image/*" />
<img id="preview" width="200" hidden />
<script>
function previewImage() {
const imageInput = document.getElementById('imageInput');
const preview = document.getElementById('preview');
const file = imageInput.files[0];
const reader = new FileReader();
reader.onload = e => {
preview.src = e.target.result;
preview.hidden = false;
};
if (file) {
reader.readAsDataURL(file);
} else {
preview.hidden = true;
}
}
</script>
○サンプルコード9:グラフの更新
<select id="graphSelect" onchange="updateGraph()">
<option value="graph1">グラフ1</option>
<option value="graph2">グラフ2</option>
</select>
<canvas id="graphCanvas" width="400" height="200"></canvas>
<script>
const graphData = {
graph1: [10, 20, 30, 40, 50],
graph2: [50, 40, 30, 20, 10]
};
const graphCanvas = document.getElementById('graphCanvas');
const ctx = graphCanvas.getContext('2d');
function updateGraph() {
const graphSelect = document.getElementById('graphSelect');
const selectedGraph = graphSelect.value;
ctx.clearRect(0, 0, graphCanvas.width, graphCanvas.height);
graphData[selectedGraph].forEach((value, index) => {
ctx.fillRect(index * 80 + 10, graphCanvas.height - value, 40, value);
});
}
updateGraph();
</script>
●注意点と対処法
○onchangeイベントは入力要素がフォーカスを失った際に発火
onchangeイベントは、要素の値が変更され、フォーカスが外れたタイミングで発火します。
しかし、場合によっては、要素の値が変更された瞬間にイベントを発火させたい場合があります。
その場合は、oninputイベントを使用しましょう。
●カスタマイズ方法
onchangeイベントは、JavaScriptで要素に追加することもできます。
これにより、コードの見通しを良くすることができます。
const selectBox = document.getElementById('selectBox');
selectBox.addEventListener('change', function() {
// 処理内容
});
まとめ
この記事を読めば、HTMLのonchangeイベントを使いこなすことができるようになります。
サンプルコードを参考に、実際に自分のプロジェクトで応用してみてください。
注意点や対処法、カスタマイズ方法も押さえておくと、より効果的にonchangeイベントを活用できます。