javascriptで、onkeyupを使用してキーが離されたイベントを取得するサンプルコードを掲載してます。ブラウザはchromeを使用しています。
環境
- OS windows11 pro 64bit
- Apache 2.4.43
- ブラウザ chrome 104.0.5112.81
onkeyup使い方
onkeyupを使用すると、キーが離されたイベントを取得することが可能です。
/* html内で利用 */
<タグ onkeyup ="イベント">
/* js内で利用 */
object.onkeyup = function(){ イベント };
onkeyup使い方(html内での使用例)
<div style="padding: 10px; margin-bottom: 10px; border: 1px dashed #333333;">
<input onkeyup="hoge()" type="text" />
</div>
<script>
'use strict';
function hoge(){
console.log('キーが離されました');
};
</script>
onkeyup使い方(js内での使用例)
<div style="padding: 10px; margin-bottom: 10px; border: 1px dashed #333333;">
<input id="main" type="text" />
</div>
<script>
'use strict';
document.getElementById('main').onkeyup = function(){
console.log('キーが離されました');
};
</script>
実行結果は、キーを離した時に、コンソールに「キーが離されました」が表示されます。
macのsafari(13.1.1)でも、同様の結果となりました。
また、以下のコードを、
document.getElementById('main').onkeyup = function(){
console.log('キーが離されました');
};
document.getElementByIdと関数をアロー化して、簡潔に記述することもできます。
main.onkeyup = () => {
console.log('キーが離されました');
};
addEventListener
addEventListenerに登録しても、同じ結果となります。
<div style="padding: 10px; margin-bottom: 10px; border: 1px dashed #333333;">
<input id="main" type="text" />
</div>
<script>
document.getElementById("main").addEventListener (
"keyup", function(){ console.log('キーが離されました')}
)
</script>
要素内の要素
「onkeyup」も「addEventListener(keyup)」も、親要素にイベントを指定すると子要素にも影響します。
<div id="main" style="padding: 10px; margin-bottom: 10px; border: 1px dashed #333333;">
<input id="sub" type="text" />
</div>
<script>
main.onkeyup = () => {
console.log('mainに変更がありました');
}
sub.onkeyup = () => {
console.log('subに変更がありました');
}
</script>
実行結果
サンプルコード
以下は、
テキストフォーム内でキーを離すと、カウントして、カウントした数を表示する
サンプルコードとなります。
※cssには「tailwind」を使用して、アロー関数で関数は定義してます。
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="utf-8">
<title>mebeeサンプル</title>
<link href="https://unpkg.com/tailwindcss@^2/dist/tailwind.min.css" rel="stylesheet">
</head>
<script>
let count = 0;
const hoge = () => {
count++;
result.innerHTML = count;
}
window.onload = () => {
sample.onkeyup = () => { hoge(); };
}
</script>
<body>
<div class="container mx-auto my-56 w-56 px-4">
<div class="flex justify-center">
<p id="result" class="bg-blue-500 text-white py-2 px-8 rounded-full mb-3 mt-4">カウント</p>
</div>
<div class="flex justify-center">
<input id="sample" type="text"
class="shadow appearance-none border border-blue-500 rounded w-full py-2 px-3 text-gray-700 mb-3 leading-tight focus:outline-none focus:shadow-outline">
</div>
</div>
</body>
</html>
カウントされていることが確認できます。
The post javascript onkeyupでキーが離されたイベントを取得する first appeared on mebee.