Development environment
table of contents __1) How to install cocoon 2) Dynamically add forms * Chikajika will be UP 3) Add id and data attributes to the form to be added __
__ I think it's difficult to read my class and id name as they are, so I use A, B, and C for easy understanding. __ I'm thinking of posting a GIF image if I feel like it soon.
$(function() {
//Don't forget the definition first.
let index = 1;
//I didn't know which class to take, so I tried it many times.(.onegai)Is an expression of that heart.
//As a result, in my case"Button to add"When"The child you want to add"I created a div that encloses all of them and gave them a class.
$('.onegai')
// 'cocoon:after-insert'This event is the key. There are other events that are executed before insertion and before / after deletion, so if you are interested, please see the official website.
.on('cocoon:after-insert', function(e, insertedItem) {
//The data attribute is added to the inserted item. When you want to pass the id.Please change after attr.
//Example).attr('id','index') **By the way, index is a variable, so anything is OK.
$(insertedItem).find('.class-a').attr('data-a', index);
$(insertedItem).find('.class-b').attr('data-b', index);
$(insertedItem).find('.class-c').attr('data-c', index);
//I'm adding one by one here.
index = index+1
//If you want to raise an event using the given data attribute, you can write it here.
//This time, when a change occurs in A, it is an event to put a value based on A in the text of B and C.
$('.class-a').on('change',function(e){
//dataA index(number)Is getting.
const dataA = $(this).attr('data-a')
const dataB = $("option:selected", this).data("b");
const dataC = $("option:selected", this).data("c");
$(`[data-b="${dataA}"]`).text(dataB)
$(`[data-c="${dataA}"]`).text(dataC)
})
})
})
__ ↓ ↓ ↓ It was a version with the explanation deleted because it was difficult to see because the explanation was described too much. If you can understand by just looking at the code, click here __
$(function() {
//Don't forget the definition first.
let index = 1;
$('.onegai')
.on('cocoon:after-insert', function(e, insertedItem) {
$(insertedItem).find('.class-a').attr('data-a', index);
$(insertedItem).find('.class-b').attr('data-b', index);
$(insertedItem).find('.class-c').attr('data-c', index);
index = index+1
$('.class-a').on('change',function(e){
const dataA = $(this).attr('data-a')
const dataB = $("option:selected", this).data("b");
const dataC = $("option:selected", this).data("c");
$(`[data-b="${dataA}"]`).text(dataB)
$(`[data-c="${dataA}"]`).text(dataC)
})
})
})
that's all.
Recommended Posts