【jQuery】動的にHTML要素を追加する処理
6416 ワード
概要
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));
});
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));
});
Author And Source
この問題について(【jQuery】動的にHTML要素を追加する処理), 我々は、より多くの情報をここで見つけました https://qiita.com/naoki-haba/items/8082f40c8f443ce5c857著者帰属:元の著者の情報は、元のURLに含まれています。著作権は原作者に属する。
Content is automatically searched and collected through network algorithms . If there is a violation . Please contact us . We will adjust (correct author information ,or delete content ) as soon as possible .