4
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

[JavaScript]異なるIDで同じ処理をまとめて書く方法

Last updated at Posted at 2022-11-11

はじめに

JavaScriptでIDは違うけれども同じ処理をまとめて書く方法がわからなかったのでここに解決法を書いておく

元のコード

function valueInput(box_id_num) {
    const box_input = document.getElementById(box_id_num).value
    console.log(box_input)
}

let boxSelect = document.getElementById('box_num0');
boxSelect.addEventListener('change', valueChange);

let boxSelect = document.getElementById('box_num1');
boxSelect.addEventListener('change', valueChange);

let boxSelect = document.getElementById('box_num2');
boxSelect.addEventListener('change', valueChange);

let boxSelect = document.getElementById('box_num3');
boxSelect.addEventListener('change', valueChange);

let boxSelect = document.getElementById('box_num4');
boxSelect.addEventListener('change', valueChange);
・
・
・

このような処理をまとめて書きたい

解決法

box_ids = []

for(var i=0;i<4;i++){
    var temp = "box_num" + i
    box_ids[i] = temp
}

このようにID名を配列に入れて

for(var i=0;i<box_ids.length;i++){
    let boxInput = document.getElementById(box_ids[i])
    boxInput.addEventListener('change', function(){
    console.log(this.value)
  });
}

このようにfor文で繰り返し処理を行うことによってまとめて書くことができる。

4
5
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?