JavaScript Formオブジェクト
JavaScriptにおいて、HTMLフォームはFormオブジェクトとして表わされる。HTML文書の各<form>タグに対してFormオブジェクトが作られる。
Elementオブジェクトのプロパティ、メソッド及びイベントもサポートする。
実装インタフェース
form オブジェクトは以下に示すインタフェースを実装している。
- EventTarget
-
- Node
-
- Element
-
- HTMLElement
-
- HTMLFormElement
document.forms
form要素は window.document オブジェクトの forms プロパティから取得できる。forms プロパティは、HTML文書に含まれる全てのform要素のコレクションである。
<form>
<input type="text" name="qty">
</form>
<form>
<input type="text" name="mail">
</form>
<script>
for (form in document.forms) {
// do something
}
</script>
個別のform要素は、0から始まる添字で指定することができる。
<form>
<input type="text" name="qty">
</form>
<form>
<input type="text" name="mail">
</form>
<script>
let form1 = document.forms[0]
let form2 = document.forms[1]
</script>
form要素にname属性を指定していれば、添字を名前で指定することができる。いわゆる連想配列である。
<form name="cart">
<input type="text" name="qty">
</form>
<form name="contact">
<input type="text" name="mail">
</form>
<script>
let cart = document.forms['cart']
let contact = document.forms['contact']
</script>
document.getElementById
form要素にid属性を指定していれば、window.document オブジェクトの getElementById メソッドでformオブジェクトを取得することができる。
<form id="cart">
<input type="text">
</form>
<script>
let form = document.getElementById('cart')
</script>
acceptCharset
form要素のaccept-charset属性の値
let acceptCharset = window.document.forms[0].acceptCharset
action
form要素のaction属性の値
<form action="https://segakuin.com/php/get.php">
<input type="text">
</form>
<script>
let action = window.document.forms[0].action
</script>
autocomplete
form要素のautocomplete属性の値
<form autocomplete="on">
<input type="text">
</form>
<script>
let autocomplete = document.forms[0].autocomplete
</script>
elements[]
フォームの全要素
let element = document.forms[0].elements[0]
for (let element in document.forms[0].elements) {
// do something
}
enctype
form要素のenctype属性の値
let enctype = document.forms[0].enctype
length
フォームの要素数
let length = document.forms[0].length
method
form要素のmethod属性の値
let method = document.forms[0].method
name
form要素のname属性の値
let name = document.forms[0].name
noValidate
form要素のnoValidate属性の値
<form novalidate>
<label for="pw">Password</label>
<input type="password" id="pw" minlength="8" maxlength="16">
</form>
<script>
if (document.forms[0].noValidate) {
/* do something */
}
</script>
target
form要素のtarget属性の値
let target = document.forms[0].target
rel
form要素のrel属性の値
let rel = document.forms[0].rel
checkValidity
checkValidity()メソッドが呼び出された場合、ユーザーエージェントはフォーム要素の制約を静的に検証し、制約検証の結果が肯定的であれば真を、否定的な結果を返した場合は偽を返す。
reset
フォームをリセットする。
var form = document.forms['cart'];
form.submit();
submit
フォームをサブミットする。
Formオブジェクトの使用例を示す。
var form = document.forms['cart'];
form.action = "/foo/addcart";
form.submit();
onreset
リセットボタンがクリックされた
onsubmit
サブミットボタンがクリックされた
参考文献
Web Hypertext Application Technology Working Group (2022) "Forms" HTML Living Standard