| 両方とも前のリビジョン前のリビジョン次のリビジョン | 前のリビジョン |
| study:javascript:jquery:clear-form [2011/03/28 08:52] – [demo] banana | study:javascript:jquery:clear-form [2017/11/28 04:26] (現在) – [code snippet] banana |
|---|
| <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> | <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> |
| <title>demo page for form reset using jQuery</title> | <title>demo page for form reset using jQuery</title> |
| |
| <link rel="stylesheet" type="text/css" media="screen" href="css/screen.css" /> | |
| |
| <script type="text/javascript" src="./test/js/jquery-1.4.2.js"></script> | <script type="text/javascript" src="./test/js/jquery-1.4.2.js"></script> |
| <tr> | <tr> |
| <td><label for="email">text field(default): </label></td> | <td><label for="email">text field(default): </label></td> |
| <td><input type="text" size="15" maxlength="70" name="email" id="txt_email" value="support@nsk.com"></td> | <td><input type="text" size="50" maxlength="70" name="email" id="txt_email" value="support@nsk.com"></td> |
| </tr> | </tr> |
| <tr> | <tr> |
| |
| </body> | </body> |
| | </html> |
| |
| | ===== code snippet ===== |
| | フォームを初期化するjqueryコードを次に示す。 |
| | <code javascript> |
| | function clearForm(){ |
| | if(confirm('データをクリアにしてよろしいですか?')){ |
| | $("input[type='text'], textarea").not("input[readonly='true'], input[type='hidden'], :button, :submit, :reset").val(""); |
| | $("input[type='radio'], input[type='checkbox'], select").removeAttr("checked").removeAttr("selected"); |
| | $("select option:first-child").attr("selected", "selected"); // 1.6以前のバージョン |
| | $("select").prop("selectedIndex", "0"); // 1.6以降 |
| | } |
| | } |
| | </code> |
| | ここで、**removeAttr("selected")**だけでは初期値に戻すことができないので、先頭のものを選択する処理を追加している。\\ |
| | 因みに、**.not("input[readonly='true']")**は読取り専用フィールドを除外する処理だけど、IEとFFで挙動が違う。\\ |
| | 詳細は下で説明する。 |
| | ===== browser issue for readonly field ===== |
| | IEで**readonly**フィルターが効くのは**readonly='true'**である。\\ |
| | FFで**readonly**フィルターが効くのは**readonly='readonly'**である。\\ |
| | ただし、**readonly**のみ書いてある場合は**readonly=''**で書かないと認識ができない。\\ |
| | ブラウザことに挙動が違うので、確実な方法は**name**で指定するのが最善だと思う。もっとスマートな方法はないのかな?? |
| | ~~DISCUSSION~~ |
| |
| |
| |
| </html> | |