LoginSignup
10
2

More than 5 years have passed since last update.

【jQuery】formの入力を一括削除

Last updated at Posted at 2018-06-02

前提

form内に複数の入力エリアがあり、
ボタンを押したら、一括ですべての入力欄の内容が消えるようにしたいと思います。

間違いや、別手法などのご助言頂けると幸いです。

コード

index.html

<form method="post" action="#">
  <input type="text" name="text">
  <input type="password" name="pass">
  <input type="number" name="num">
  <button type="button" id="del-btn">入力削除</button>
</form>

deleteAll.js

$(function()
{
  $('#del-btn').on('click',function()
  {
    $(this).parent('form').find(':text').val("");
    $(this).parent('form').find(':password').val("");
    $(this).parent('form').find('input[type="number"]').val("");
  });
});

解説

削除ボタンが押されたら、
自身の親要素のformの中から、inputのそれぞれ探して,valを書き換えています。
$(this).parent('form')としているのは、複数formがある時対策です。
この構造の場合findじゃなくて、children()でも良いです。

formが一つであるなら、

deleteAll.js

$(function()
{
  $('#del-btn').on('click',function()
  {
    $('form').find(':text').val("");
    $('form').find(':password').val("");
    $('form').find('input[type="number"]').val("");
  });
});

メソッドチェーンを使って繋げることも出来ます。

index.html

$(function()
{
  $('#del-btn').on('click',function()
  {
    $('form').find(':text').val("").end()
        .find(':password').val("").end()
            .find('input[type="number"]').val("");
  });
});

10
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10
2