フォーム全体の入力を禁止する:javascript
[同意する]のラジオボタンを選択するとフォームに書き込めるようになる
という申し込みフォームを作る必要があったのでそのやり方をメモ。
[同意する]→[次へ] サンプル
みたいに一つだけの要素にする場合は
html記述
<form action="#" id="form" name="form"> <p> <label> <input type="radio" name="kyoka" id="no" checked="checked"> 同意しない </label> <label> <input type="radio" name="kyoka" id="yes"> 同意する </label> </p> <p><input type="submit" id="next" value="次へ" disabled="disabled" /></p> </form>
javascript記述
window.onload = function(){ document.getElementById("yes").onclick = function(){ document.getElementById("next").disabled = false; } document.getElementById("no").onclick = function(){ document.getElementById("next").disabled = true; } }
みたいに記述すればいいのですが、
要素が多い場合はめんどうなので
今回はフォーム全体を一気にするやり方をします。
javascriptの記述
function setForm(formObj,flag) { num = formObj.elements.length; //要素の数の取得 for (i=0; i<num; i++) formObj.elements[i].disabled = flag; }
htmlの記述
<body onload="setForm(document.form1,true)"><!--フォームの初期値の指定--> <p> <label> <input type="radio" name="kyoka" onclick="setForm(document.form1,true)" checked="checked"> 同意しない </label> <label> <input type="radio" name="kyoka" onclick="setForm(document.form1,false)"> 同意する </label> </p> <form action="#" name="form1"> <input type="text" name="text"><br /> <input type="checkbox">チェックボックス<br /> <input type="radio">ラジオボタン<br /> <textarea>テキストエリア</textarea><br /> <input type="button" value="ぼたん"><br /> <button type="submit">送信</button> </form> </body>
という感じで完成!
ちなみに
<p> <a href="javaScript:setForm(document.form1,true)">同意しない</a> <a href="javaScript:setForm(document.form1,false)">同意する</a> </p>
みたいな書き方でもOK。
完成サンプルはこちら→サンプル
参考サイト
http://www.openspc2.org/reibun/javascript/form/007/
JavaScriptのおすすめ参考書
ポチップ
ポチップ