フォームのすべての入力フィールドとtextareaフィールドをクリアしたいのですが。これは、reset
クラスの入力ボタンを使用した場合、以下のように動作します。
$(".reset").bind("click", function() {
$("input[type=text], textarea").val("");
});
これにより、フォームのフィールドだけでなく、ページ上のすべてのフィールドがクリアされます。実際のリセットボタンのあるフォームだけを対象とした場合、セレクタはどのようになりますか?
jQuery 1.6+に対応しています。
$(':input','#myform')
.not(':button, :submit, :reset, :hidden')
.val('')
.prop('checked', false)
.prop('selected', false);
jQuery < 1.6 の場合。
$(':input','#myform')
.not(':button, :submit, :reset, :hidden')
.val('')
.removeAttr('checked')
.removeAttr('selected');
こちらの記事をご覧ください。 https://stackoverflow.com/questions/680241/blank-out-a-form-with-jquery
または
$('#myform')[0].reset();
jQueryとして提案。
.prop()]propメソッドを使って、フォーム要素の checked
, selected
, disabled
などの DOM プロパティを取得したり変更したりします。
なぜJavaScriptを使わなければならないのでしょうか?
<form>
<!-- snip -->
<input type="reset" value="Reset"/>
</form>
http://www.w3.org/TR/html5/the-input-element.html#attr-input-type-keywords
この方法を試してみましたが、デフォルト値を持つフィールドはクリアされませんでした。
そこで、jQueryを使った方法をご紹介します。
$('.reset').on('click', function() {
$(this).closest('form').find('input[type=text], textarea').val('');
});