[英]How to insert and get the value of a dynamically created input field using javascript?
[英]How can I get data from dynamically created input field using vanilla JavaScript?
HTML:在 'education-field' div 內,將通過單擊添加更多按鈕創建動態輸入字段。 創建輸入字段后,我想獲取該字段的數據。 這實際上是為表單驗證完成的。 用戶可以添加更多字段來添加他們的教育程度。 但我無法跟蹤輸入字段的數據。
<form>
<div class="education-field">
<!-- input field -->
</div>
<button style=" background-color: blueviolet; border-color: blueviolet;" class="btn btn-primary btn-sm add-button"> Add more </button>
</form
javascript:此代碼用於在教育字段內添加動態輸入字段。
const addField = document.querySelector('.add-button');
const educationField = document.querySelector('.education-field');
addField.addEventListener('click', () => {
const buttonDiv = document.querySelector('.add-more-field');
const div = document.createElement('div')'
div.classList.add('education-input-field', 'row', 'mb-2');
div.innerHTML = `<div class="col-md-5">
<input
type="text"
class="form-control degree-name"
placeholder="Degree name "
/>
</div>
`;
educationField.insertBefore(div, buttonDiv);
})
要獲取所有字段值,請使用querySeletorAll
和 map 將每個輸入元素的值放入一個數組
// Utility functions: const EL = (sel, par) => (par||document).querySelector(sel); const ELS = (sel, par) => (par||document).querySelectorAll(sel); const ELNew = (tag, prop) => Object.assign(document.createElement(tag), prop) // App: Form: Add education: const EL_add = EL(".add-button"); const EL_get = EL(".get-button"); const EL_fields = EL(".education-fields"); const addField = (name) => { const EL_field = ELNew("div", { className: "education-input-field row mb-2", innerHTML: `<div class="col-md-5"> <input value="${name || ""}" type="text" class="form-control degree-name" placeholder="Degree name"/> </div>` }); EL_fields.append(EL_field); } const getFieldsVaules = () => { return [...ELS(".degree-name", EL_fields)].map(el => el.value); }; // Events: EL_add.addEventListener("click", () => { // Add a new field to DOM addField(); }); EL_get.addEventListener("click", () => { const fieldsValues = getFieldsVaules(); // Get all fields values into array console.log(fieldsValues); // TODO: do something with it }); // Example: prepopulate with existing fields: const existingFields = ["JavaScript Course", "HTML course"]; existingFields.forEach(addField); // That simple!
.btn.btn-primary { background-color: blueviolet; border-color: blueviolet; color: #fff; }
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css"> <div class="education-fields"></div> <button type="button" class="btn btn-primary add-button">Add more</button> <button type="button" class="btn btn-secondary get-button">Get Current values</button>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.