3

以下のコードスニペットで誰かが私を助けてくれることを願っています。ボタンがクリックされたときに、サイトのフォーム フィールドを複製しようとしています。

問題は、同じ html ページ上の複数のフォームに対してこれを機能させるのに問題があることです。これは最初のフォームでのみ機能します。2 番目のフォームを追加しようとすると、2 番目のフォームのボタンが 2 番目のフォーム内の最初のフォームを複製します。どんな洞察も大歓迎です!

HTML

<div class="duplicate-sections">
 <div class="form-section">
    <fieldset>
      <p>
        <label for="firstName">First Name:</label>
        <input name="firstName[]" id="firstName" value="" type="text" />
      </p>
      <p>
        <label for="lastName">Last Name:</label>
        <input name="lastName[]" id="lastName" value="" type="text" />
      </p>
        <a href="#" class="remove">Remove Section</a>
    </fieldset>
  </div>
</div>

<a href="#" class="addsection">Add Section</a>

Jクエリ

//define template
var template = $('.duplicate-sections .form-section:first').clone();

//define counter
var sectionsCount = 1;

//add new section
$('body').on('click', '.addsection', function() {

    //increment
    sectionsCount++;

    //loop through each input
    var section = template.clone().find(':input').each(function(){

        //set id to store the updated section number
        var newId = this.id + sectionsCount;

        //update for label
        $(this).prev().attr('for', newId);

        //update id
        this.id = newId;

    }).end()

    //inject new section
    .appendTo('.duplicate-sections');
    return false;
});

//remove section
$('.duplicate-sections').on('click', '.remove', function() {
    //fade out section
    $(this).parent().fadeOut(300, function(){
        //remove parent element (main section)
        $(this).parent().parent().empty();
        return false;
    });
    return false;
});
4

1 に答える 1

0

ワーキングコードペン

アクションのこの部分を変更する必要がありますremove:

$(this).parent().fadeOut(300, function(){
    //remove parent element (main section)
    $(this).parent().parent().empty();
    return false;
});

することが :

$(this).closest('.form-section').fadeOut(300, function(){
    $(this).closest('.form-section').empty();
});

closest()関数と特定のクラスを使用してform-section、親 div をターゲットにします。また、交換する必要があります:

.appendTo('.duplicate-sections');

に :

.appendTo($(this).prev('.duplicate-sections'));

クラスだけでセレクターを残すとduplicate-sections、新しいフォームがこのクラスのすべての要素に追加されるため、クリックされた href に関連するものを指定する必要がありますAdd Section

最後に行うことは、すべての追加セクション リンクに追加の属性data-sectionを追加して、フォームの番号 (0 ベース) を指定することです。

<a href="#" class="addsection" data-section='0'>Add Section</a>

次に、すべてのフォームを配列に格納します。

var forms = [];

$('.duplicate-sections .form-section').each(function(){
  forms.push($(this).clone());                
})

そして、次を使用してクリックされたリンクで関連するフォームを取得します。

var template = forms[$(this).data('section')];

お役に立てれば。

于 2016-11-08T23:12:50.223 に答える