javascript textareaのrequired属性の状態を取得する
- 作成日 2021.06.11
- 更新日 2022.09.02
- javascript
- javascript

javascriptで、textareaのrequired属性の状態を取得するサンプルコードを掲載してます。ブラウザはchromeを使用しています。
環境
- OS windows11 pro 64bit
- Apache 2.4.43
- ブラウザ chrome 104.0.5112.101
状態を取得
「required」の状態を取得する場合は、「required」プロパティを確認することで可能です。
「true」なら設定されていて、「false」なら設定されてない状態です。
<textarea id="hoge" required></textarea>
<input id="btn" type="button" value="ボタン" />
<script>
'use strict';
document.getElementById('btn').onclick = function(){
const elm = document.getElementById('hoge')
// コンソールに出力
console.log(elm.required);
}
</script>
実行結果を確認すると、「required」が設定されているので「true」が帰ってくることが確認できます。

複数一括で取得/変更
例えば「class」名を指定して、一括で取得/変更する場合は以下のように「forEach」を使用します。
※「HTMLCollection」は配列に変更すると「forEach」が使用できます。
<textarea class="hoge" required></textarea>
<textarea class="hoge"></textarea>
<textarea class="hoge" required></textarea>
<input id="btn" type="button" value="ボタン" />
<script>
document.getElementById('btn').onclick = function () {
const elm = document.getElementsByClassName("hoge");
[...elm].forEach(function (v) { console.log( v.required ) });
}
</script>
実行結果

コードの簡略化
また、以下のコードを、
document.getElementById('btn').onclick = function(){
const elm = document.getElementById('hoge')
// コンソールに出力
console.log(elm.required);
}
アロー関数とdocument.getElementByIdを省略して、簡潔に記述することもできます。
btn.onclick = () =>{
console.log(hoge.required);
}
サンプルコード
以下は、
「実行」ボタンをクリックして、textareaのrequiredの状態を切り替えて、状態を出力するサンプルコードとなります。
※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>
const hoge = () => {
txt.required ? txt.required = false : txt.required = true;
disp.innerHTML = txt.required;
}
window.onload = () => {
btn.onclick = () => { hoge() };
}
</script>
<body>
<div class="container mx-auto my-56 w-64 px-4">
<div id="sample" class="flex flex-col justify-center">
<h2 id="disp" class="font-semibold text-lg mr-auto">状態</h2>
<div class="mb-3 md:space-y-2 w-full text-xs">
<textarea id="txt" class="w-full min-h-[100px] max-h-[300px] h-28 appearance-none block w-full bg-grey-lighter text-grey-darker border border-grey-lighter rounded-lg py-4 px-4" required></textarea>
</div>
<button id="btn" class="mb-2 md:mb-0 bg-green-400 px-5 py-2 text-sm shadow-sm font-medium tracking-wider text-white rounded-full hover:shadow-lg hover:bg-green-500">
実行
</button>
</div>
</div>
</body>
</html>
実行結果を確認すると、requiredが切り替わって状態が表示されていることが確認できます。

-
前の記事
Ruby モジュールの簡単な使い方 2021.06.10
-
次の記事
python numpyを使って配列を指定した範囲と分割する数で作成する 2021.06.11
コメントを書く