前回に引き続きフォーム部品のまとめです。今回はプログラム側から値をセットしたり選択状態をコントロールするお話です。
前回のフォームに入力された値を取得したいという方は以下をどうぞ。
目次
テキストボックス
getElementById
やquerySelector
などで取得したオブジェクトのvalueプロパティに値を代入するだけです。
<form>
<input type="text" id="foo">
<input type="text" name="bar">
</form>
<script>
window.addEventListener('load', ()=>{
document.getElementById('foo').value = 'foo';
document.querySelector('input[type=text][name=bar]').value = 'bar';
})
</script>
以下のフォーム部品も同じ要領でセットできます。
- パスワード (
<inputy type="password">
) - 隠しフィールド (
<inputy type="hidden">
) - テキストエリア (
<textarea>
)
プルダウン(ドロップダウン)
選択する(単一)
プルダウンの項目を選択するにはテキストボックスと同様にvalueプロパティに指定するだけです。
<form>
<select id="fruits">
<option value="apple">りんご</option>
<option value="banana">バナナ</option>
<option value="orange">オレンジ</option>
</select>
</form>
<script>
window.addEventListener('load', ()=>{
// バナナを選択する
document.getElementById('fruits').value = 'banana';
})
</script>
選択する(複数)
複数選択する場合も同様です。数がある場合はループなどで回しながらセットします。
<form>
<select id="fruits" size="3" multiple>
<option value="apple">りんご</option>
<option value="banana">バナナ</option>
<option value="orange">オレンジ</option>
</select>
</form>
<script>
window.addEventListener('load', ()=>{
// りんごとオレンジを選択する
document.querySelector('#fruits option[value=apple]').selected = true;
document.querySelector('#fruits option[value=orange]').selected = true;
})
</script>
追加する
選択肢を増やしてみます。select要素にaddやinsertBeforeメソッドでoption要素を追加してやります。
<form>
<select id="fruits">
<option value="apple">りんご</option>
<option value="banana">バナナ</option>
<option value="orange">オレンジ</option>
</select>
</form>
<script>
window.addEventListener('load', ()=>{
const fruits = document.getElementById('fruits');
// 最後に追加する
fruits.add(new Option('みかん', 'mikan'));
// 先頭に追加する
fruits.insertBefore(new Option('もも', 'peach'), fruits.firstChild);
// りんごの後ろに追加する
fruits.insertBefore(new Option('ぶどう', 'grape'), fruits.children[2]);
})
</script>
createElementを使う方法でも同様に動きます
const option = document.createElement('option');
option.value = 'peach';
option.text = 'もも';
fruits.insertBefore(option, fruits.firstChild);
チェックボックス
ここではチェックボックスの選択状態をコントロールします。
選択する(単一)
チェックボックスのvalueには選択されたときの値が入っていますので、選択情報を指定するのはchecked
プロパティです。
<form>
<input type="checkbox" name="terms" id="terms" value="1"><label for="terms">利用規約に同意</label>
</form>
<script>
window.addEventListener('load', ()=>{
document.getElementById('terms').checked = true
})
</script>
選択する(複数)
複数同時に入れたい場合も同様です。
<form>
<input type="checkbox" name="fruits" id="fruits1" value="apple"><label for="fruits1">りんご</label>
<input type="checkbox" name="fruits" id="fruits2" value="banana"><label for="fruits2">バナナ</label>
<input type="checkbox" name="fruits" id="fruits3" value="orange"><label for="fruits3">オレンジ</label>
</form>
<script>
window.addEventListener('load', ()=>{
// りんごとオレンジにチェックを入れる
document.getElementById('fruits1').checked = true;
document.getElementById('fruits3').checked = true;
})
</script>
ラジオボタン
チェックボックスと同様にvalueには選択されたときの値が入っていますのでchecked
プロパティで選択状態をコントロールします。
<form>
<input type="radio" name="hardness" id="hardness1" value="1"><label for="hardness1">かため</label>
<input type="radio" name="hardness" id="hardness2" value="2"><label for="hardness2">普通</label>
<input type="radio" name="hardness" id="hardness3" value="3"><label for="hardness3">やわらかめ</label>
</form>
<script>
window.addEventListener('load', ()=>{
// やわらかめを選択する
document.querySelector('#hardness3').checked = true;
})
</script>
ファイル(設定できません)
ファイルのvalueはJavaScriptから設定できません。以下のコードで動きそうな気がしますが、実際には例外が発生します。
<form>
<input type="file" id="avatar">
</form>
<script>
window.addEventListener('load', ()=>{
document.getElementById('avatar').value = 'foo.png';
});
</script>
「プロパティの設定に失敗した。プログラムからは空文字列(value=''
)しか受け付けない」といった内容のエラーメッセージが出力されます。
Uncaught DOMException: Failed to set the ‘value’ property on ‘HTMLInputElement’: This input element accepts a filename, which may only be programmatically set to the empty string.
参考ページ
- Node.insertBefore() – Web API | MDN
- HTMLSelectElement.add() – Web API | MDN
- Document.createElement() – Web API | MDN
このブログを応援する
お寄せいただいたお気持ちは全額サーバ代や次の記事を執筆するための原資として活用させていただいております。この記事が参考になった場合などぜひご検討ください。