LoginSignup
32
31

More than 5 years have passed since last update.

追加できるフォーム(jQuery)

Last updated at Posted at 2015-08-21

初投稿。もう既出のネタかと思いますが、、、

index.html
<div id="form">
  <input type="text">
</div>
<input type="button" value="+" id="addForm">
script.js
$(function(){
  $('#addForm').click(function(){
    $('#form').append('<input type="text">');
  });
});

これで追加できるようになります。
ちなみに、値の取得は、

script.js
var value;
var forms = $('input[type=text]');
for (var i = 0 + 1;i < forms.length + 1;i++) {
  value = $('input[type=text]:nth-of-type(' + i + ')').val();
  // これで、変数valueにフォームの中身が格納されたので、あとはここでAjaxとかするだけ。
}

です。
「nth-child」じゃなくて「nth-of-type」にするほうが、バグが起こりにくいです。
追加の上限を設定する場合は、

index.html
<div id="form">
  <input type="text" data-inputCount="0">
</div>
<input type="button" value="+" id="addForm">
script.js
$(function(){
  $('#addForm').click(function(){
    var inputCount = $('#form input:last-child').attr('data-inputCount');
    var next_num = parseInt(inputCount) + 1;
    if(next_num == 10/* ←上限 */) {
      $('#addForm').remove();
    } else {
      $('#form').append('<input type="text" data-inputCount="' + next_num + '">');
    }
  });
});

たぶんこれでいいと思います。

2015.08.21 追記
@naga3 さんに、よりシンプルなコードを教えていただいたので、追記します。
値の取得はchildrenとeachを使った方がいい:

script
var forms = $('#form').children();
forms.each(function() {
  var value = $(this).val();
  // これで、変数valueにフォームの中身が格納されたので、あとはここでAjaxとかするだけ。
});

上限を設定するときもこんなに簡潔に書ける:

script
$('#addForm').click(function(){
  if ($('#form').children().length < 10) {
    $('#form').append('<input type="text">');
  }
});

ありがとうございます!

32
31
2

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
32
31