【jQuery】動的にHTML要素を追加する処理


概要

jQueryをつかって要素を動的に追加する処理を実装したので残す

HTML要素

index.blade.php
<label class="col-md-2 col-form-label text-md-right">
    URL
</label>
<div class="col-md-12 mb-4 domain_area">
    <input type="url" name="url[]" class="form-control"
           value="" placeholder="https://example.com/">
</div>
<div class="col-md-2">
    <input type="button" value="+" class="add btn btn-secondary">
    <input type="button" value="-" class="del btn btn-secondary">
</div>
index.js
$(function () {
    /**
     * @summary 項目追加
     * @param target
     */
    const addForm = (target) => {
        $(target).parent().prev('.domain_area').clone(true).insertBefore($(event).parent());
    }

    /**
     * @summary 項目削除
     * @param target
     */
    const delForm = (target) => {
        const nowRowCount = $('.domain_area').length - 1;

        if (nowRowCount >= 1) {
            $(target).parent().prev('.domain_area').remove();
        }
    }

    $(document).on("click", ".add", (event) => addForm(event.currentTarget));

    $(document).on("click", ".del", (event) => delForm(event.currentTarget));
});