I am facing some challenges with JavaScript. I want to dynamically add a form to my HTML document when the user clicks on a button. Here is the code I have written:
plusBtn.addEventListener('click', () => {
const newLine = document.createElement('div');
newLine.classList.add('line');
newLine.innerHTML = `
<textarea form="shopForm" class="form-control form-data" name="comment" id="comment" rows="3" placeholder="Comment" required></textarea>
<input form="shopForm" type="text" class="form-control form-data" name="price" id="price" placeholder="Price" required>
<input form="shopForm" class="form-data" type="number" name="amount" id="amount" required>`;
dataForm.append(newLine);
});
Furthermore, I need to format the form data in a custom way with multiple items. The issue I am facing is that since the inputs are dynamically added using JavaScript, I am unable to access them using .querySelectorAll
.
dataForm.addEventListener('submit', function(e) {
e.preventDefault();
console.log(window);
const formData = new FormData(dataForm),
comment = document.querySelectorAll('.form-comment'),
price = document.querySelectorAll('.form-price'),
amount = document.querySelectorAll('.form-amount');
console.log(comment);
formData.append('product_url', productUrl.value);
formData.append('user_id', userId);
formData.append('delivery_type_id', delivery.value);
formData.append('package_type_id', package.value);
if (comment.length > 1) {
let items = [];
comment.forEach((item, i) => {
let obj = {};
obj.comment = item.value;
obj.price = price[i].value;
obj.amount = amount[i].value;
items.push(obj);
});
formData.append('items', JSON.stringify(items));
} else {
let items = [];
items.push({
'comment': comment[0].value,
'price': price[0].value,
'amount': amount[0].value
});
formData.append('items', JSON.stringify(items));
}
dataAjaxSend(formData)
.then((response) => {
console.log(JSON.parse(response));
})
.catch((err) => console.log('Error' + err))
});
I am seeking guidance on creating and accessing dynamically added inputs. Thank you for your assistance)