jQueryフォームイベントの例
jQueryには、フォーム要素の動作を処理するための5つの一般的なフォームイベントが付属しています。
1. focus()
要素がフォーカスされているときに起動します。
$("input,select,textarea").focus(function () { //do something });
2. blur()
要素がフォーカスを失ったときに起動します。
$("input,select,textarea").blur(function () { //do something });
3. change()
要素の値が変更されたときに起動します。たとえば、チェックボックス、ラジオボタン、またはテキストボックスの値を更新します。
$("input,select,textarea").change(function () { //do something });
4. select()
要素内のテキストを強調表示するときに起動します。テキストボックスまたはテキストエリアのみに制限されます。
$("input,textarea").focus(function () { //do something });
5. submit()
フォームを送信しようとすると起動し、フォーム要素にのみバインドします。
$("form").focus(function () { //do something });
自分で試してみてください
<html> <head> <script type="text/javascript" src="jquery-1.3.2.min.js"></script> <style type="text/css"> div{ padding:16px; } .focus, .blur, .change, .select{ color:white; border:1px solid red; background-color:blue; padding:8px; margin:8px; } </style> </head> <body> <h1>jQuery form events - focus(), change(), blur(), select(), submit() example</h1> <form name="testing" action="#"> <div> TextBox : <input type="textbox" size="50"></input> </div> <div> <label style="float:left">TextArea : </label> <textarea cols="30" rows="5"></textarea> </div> <div> Radio : <input name="sex" type="radio" value="Male" checked>Male</input> <input name="sex" type="radio" value="Female">Female</input> </div> <div> CheckBox : <input type="checkbox" name="checkme">Check Me</input> </div> <div> Country : <select id="country"> <option value="China">China</option> <option value="United State">United State</option> </select> </div> <div> <input type="submit"></input> <input type="reset"></input> </div> </form> <script type="text/javascript"> $("input,select,textarea").focus(function () { $(this).after("<span class='focus'> focus() triggered! </span>"); $("span").filter('.focus').fadeOut(4000); }); $("input,select,textarea").blur(function () { $(this).after("<span class='blur'> blur() triggered! </span>"); $("span").filter('.blur').fadeOut(4000); }); $("input,select,textarea").change(function () { $(this).after("<span class='change'> change() triggered! </span>"); $("span").filter('.change').fadeOut(4000); }); $("input,textarea").select(function () { $(this).after("<span class='select'> select() triggered! </span>"); $("span").filter('.select').fadeOut(4000); }); $("form").submit(function () { alert('Form submitted!'); }); </script> </body> </html>
リンク://wp-content/uploads/jQuery/jQuery-form-events.html[デモを試してください]