Node.js+Express+MongoDB下多textarea提交及动态增删问题求助
Fixing Dynamic Textarea Issues in Your Node/Express/MongoDB App
Hey there! Let's work through your two problems and add the delete functionality you want. Here's a breakdown of the fixes and modified code:
1. Problem: Can't retrieve values from dynamically added textareas
Root Cause
Your current submit handler only targets the initial textareas by their exact name attributes. Dynamically added ones have inconsistent or missing names, so they're not being included in your form data.
Solution
- Use array-style names (like
updateTextarea[]) for all textareas of the same type — this lets you easily collect all values at once. - Update your submit logic to loop through all matching textareas and gather their values into an array.
2. Problem: Dynamic textareas appear below the submit button
Root Cause
You're appending new textareas directly to the .row element, which places them at the end of the row (after your submit button).
Solution
- Create dedicated containers for update and notification textareas. Append new elements to these containers to keep them grouped with their original textareas.
- Add delete buttons to each dynamic textarea, and use event delegation to handle clicks on these dynamically created buttons.
Modified HTML Code
<div class="container"> <div class="row"> <h5> New updates/Notifications </h5> <div class="input-field col s11"> <select class="moduleSelect" id="getOptionValue"> <option value="" disabled selected>Choose Module</option> </select> </div> <!-- Dedicated container for update textareas --> <div class="update-textareas"> <div class="input-field col s11"> <textarea name="updateTextarea[]" class="materialize-textarea"></textarea> <label>Update area</label> </div> <div class="col s1 addButtonUpdate"> <i class="material-icons small icon-demo">add_circle</i> </div> </div> <!-- Dedicated container for notification textareas --> <div class="notification-textareas"> <div class="input-field col s11"> <textarea name="notificationTextarea[]" class="materialize-textarea"></textarea> <label>Notification area</label> </div> <div class="col s1 addButtonNotify"> <i class="material-icons small icon-demo">add_circle</i> </div> </div> <div class="col s6 right buttonGroup "> <a class="waves-effect waves-light btn submitButton">Submit</a> </div> </div> </div>
Modified JavaScript Code
$(document).ready(function() { var getOptions = ajaxServices("/iotsupport/modules/getModules", "GET"); if (getOptions.status == 201) { for (var i in getOptions.body) { var option = getOptions.body[i].moduleName; var optionDiv = document.createElement('option'); $(optionDiv).text(option); $('.moduleSelect').append(optionDiv); } } else if (getOptions.status == 401) { swal({ title: "", text: "Error fetching the query options", icon: "error", button: "OK" }) } $('select').material_select(); // Submit handler: collect all textarea values $(".submitButton").on('click', function(e) { var optionList = $("#getOptionValue").val(); console.log(optionList); // Collect all update textarea values var updateFieldValues = []; $("textarea[name='updateTextarea[]']").each(function() { var val = $(this).val().trim(); if (val) updateFieldValues.push(val); }); // Collect all notification textarea values var notificationFieldValues = []; $("textarea[name='notificationTextarea[]']").each(function() { var val = $(this).val().trim(); if (val) notificationFieldValues.push(val); }); var sendObject = { "moduleName": optionList, "updateObject": updateFieldValues, // Send array of values "notifyObject": notificationFieldValues // Send array of values }; var responseObject = ajaxServices("/iotsupport/addUpdateNotify/postUpdateNotify", "POST", sendObject); console.log(responseObject); if (responseObject.status == 401) { alert("Some error occurred"); } else if (responseObject.status == 201) { alert("Update/notification saved successfully."); location.reload(); } }); // Add new update textarea with delete button $(".addButtonUpdate").on('click', function(e) { var inputArea = ` <div class="input-field col s10"> <textarea name="updateTextarea[]" class="materialize-textarea"></textarea> <label>Update area</label> </div> <div class="col s1 delete-btn"> <i class="material-icons small icon-demo">delete</i> </div> `; // Append to update container (before the add button) $(this).closest('.update-textareas').append(inputArea); }); // Add new notification textarea with delete button $(".addButtonNotify").on('click', function(e) { var inputArea = ` <div class="input-field col s10"> <textarea name="notificationTextarea[]" class="materialize-textarea"></textarea> <label>Notification area</label> </div> <div class="col s1 delete-btn"> <i class="material-icons small icon-demo">delete</i> </div> `; // Append to notification container (before the add button) $(this).closest('.notification-textareas').append(inputArea); }); // Handle delete button clicks (event delegation for dynamic elements) $(document).on('click', '.delete-btn', function() { $(this).closest('.input-field').remove(); }); });
Key Notes
- Array-style names: Using
updateTextarea[]ensures all update textareas are grouped, making it easy to collect their values into an array. - Dedicated containers:
.update-textareasand.notification-textareaskeep new elements grouped with their original counterparts, so they don't end up below the submit button. - Event delegation: The delete button click handler uses
$(document).on('click', '.delete-btn', ...)because dynamic elements aren't present when the page loads. - Backend adjustment: Make sure your Express/MongoDB endpoint expects arrays for
updateObjectandnotifyObject(instead of single values) to store all the textarea entries.
内容的提问来源于stack exchange,提问作者Hema Krishna
相关产品推荐
相关产品推荐

