mk_5884 Programming

自分で調べたIT関連のことなどを書いています

複数のformのsubmit時のjsを変数化してひとつにまとめる

1ページ内にformが2つあって、submit押した時のjs を同じものを呼びたい。
で、formのnameやcheckboxのnameを変数化したい場合は、以下の様にやります。

<html>
<head>

<script type="text/javascript">
function test(obj) {
    //obj.name -> formのname
    //obj.childNodes[1].name -> checkboxのname これ、ieとffで処理が違ったような・・・
    console.log(document.forms[obj.name].elements[obj.childNodes[1].name].length)
    console.log(obj.childNodes[1].name);
    return false;
}
</script>

</head>
<body>

<form name="aaa" onclick="return test(this)">
    <input type="checkbox" value="1" name="koba">あああ<br>
    <input type="checkbox" value="2" name="koba
">いいい<br>
    <input type="checkbox" value="3" name="koba">ううう<br>
    <input type="checkbox" value="4" name="koba
">えええ<br>
    <input type="checkbox" value="5" name="koba">おおお<br>
    <input type="submit" value="送信1"><br>
</form>

<form name="bbb" onclick="return test(this)">
    <input type="checkbox" value="1" name="masa
">あああ<br>
    <input type="checkbox" value="2" name="masa">いいい<br>
    <input type="checkbox" value="3" name="masa
">ううう<br>
    <input type="checkbox" value="4" name="masa[]">えええ<br>
    <input type="submit" value="送信2"><br>
</form>

</body>
</html>

▼参考
基礎第六回 — JavaScript初級者から中級者になろう — uhyohyo.net
← js内のformの取得方法
子ノードの取得 - DOM入門 - JavaScript入門