LoginSignup
2
1

More than 3 years have passed since last update.

TypeScriptでチェックが入ったチェックボックスの値のみを取得する方法

Last updated at Posted at 2021-01-24

実現したいこと

「チェックボックスにチェックをして、削除ボタンを押すと、チェックされた項目が一括削除される」という、よくある処理をTypeScriptで行いたい。
そのためには、チェックボックスにチェックの入った要素だけを取得する必要がある。

スクリーンショット 2021-01-24 19.31.46.png

結論

チェックボックスのHTML

index.html
<td><input type="checkbox" name="checkBox" value="1"></td>
<td><input type="checkbox" name="checkBox" value="2"></td>
<td><input type="checkbox" name="checkBox" value="3"></td>
<td><input type="checkbox" name="checkBox" value="4"></td>

チェックボックスにチェックの入った要素を配列で返す関数

App.ts
const checkBoxes = document.getElementsByName('checkBox');

const checkedArray = (checkboxes: NodeList): HTMLElement[] => {
    let resultArray: HTMLElement[] = Array.prototype.slice.call(checkboxes).filter(checkbox => checkbox.checked)

    return resultArray
}

checkedArray(checkBoxes)

解説

まずは、チェックボックス全部を取得します。

App.ts
const checkBoxes = document.getElementsByName('checkBox');

次に、取得した要素(checkBoxes)の中から、チェックの入った要素のみを配列で返す関数を作ります。
ドキュメントにある通り、getElementsByNameNodeListを返すので、

App.ts
const checkedArray = (checkboxes: NodeList): HTMLElement[] => {
}

引数をNodeList型に指定して、返り値をHTMLElementの配列に指定します。

引数として渡ってきたcheckboxesの中からチェックの入った要素のみを判別して配列に入れたいのですが、

App.ts
let resultAry: HTMLElement[] = checkboxes.filter(checkbox => checkbox.checked)
// => Property 'filter' does not exist on type 'NodeList'.

NodeListfileterは使えないとエラーが出ます。

なので、

App.ts
let resultAry: HTMLElement[] = Array.prototype.slice.call(checkboxes).filter(checkbox => checkbox.checked)

Array.prototype.slice.call()を使ってfiltercheckedの要素のみを配列に入れます。

あとは結果の配列をreturnすればOK👍🏻

App.ts
const checkedArray = (checkboxes: NodeList): HTMLElement[] => {
    let resultArray: HTMLElement[] = Array.prototype.slice.call(checkboxes).filter(checkbox => checkbox.checked)

    return resultArray
}

いざ実行

スクリーンショット 2021-01-24 20.55.20.png

App.ts
let checkedElements = checkedArray(checkBoxes);
console.log(checkedElements);

以下の要素がコンソールに出力される

<td><input type="checkbox" name="checkBox" value="1"></td>
<td><input type="checkbox" name="checkBox" value="3"></td>

1/25 追記

@vf8974 様より、コメントでウルトラ超シンプルな記述を教えていただきました!

App.ts
const checkBoxes = document.querySelectorAll('input[type=checkbox]:checked');

1行で書けた…

ここから値を取り出して配列にしたい時は、

forEachを使ったり、

App.ts
const checkBoxes = document.querySelectorAll('input[type=checkbox]:checked');

let values = [];
checkBoxes.forEach(node => values.push(node.nodeValue));

console.log(values);
// ["1", "3"]

mapを使えばいい感じ。

App.ts
const checkBoxes = document.querySelectorAll('input[type=checkbox]:checked');

let values = Array.prototype.slice.call(checkBoxes).map(element => element.value);

console.log(values);
// ["1", "3"]

バージョン情報

TypeScript 4.1.3

2
1
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
2
1