jQuery动态添加复选框的标签递增与值获取问题
Hey there! Let's tackle your two main problems head-on: getting section numbering to work correctly across different category boxes, and implementing the Save button to capture each category's data.
1. Fixing Section Numbering Across Categories
The root issue here is that you're probably using a global counter for sections, which doesn't track counts per category box. Instead, we'll store the section count directly on each category box using a data attribute, so each blue box keeps its own tally.
Here's the Updated Code:
First, let's set up the base HTML structure (I'll assume you have something like this):
<div id="categories-container"></div> <button id="add-category-btn">Add Category</button> <button id="save-btn">Save</button>
Now the JavaScript to handle adding categories and sections:
// Add Category functionality document.getElementById('add-category-btn').addEventListener('click', () => { const categoryBox = document.createElement('div'); categoryBox.className = 'category-box'; // Your blue box class categoryBox.setAttribute('data-section-count', '1'); // Initialize section count to 1 // Build the first section (Section 1) const firstSection = buildSection(1); // Add category content: input, first section, add section button categoryBox.innerHTML = ` <input type="text" class="category-title" placeholder="Category Name"> ${firstSection} <button class="add-section-btn">Add Section</button> `; document.getElementById('categories-container').appendChild(categoryBox); }); // Helper function to build a section element function buildSection(sectionNumber) { return ` <div class="section-group"> <h3>Section ${sectionNumber}</h3> <div class="checkbox-group"> <label><input type="checkbox" value="item1"> Item 1</label> <label><input type="checkbox" value="item2"> Item 2</label> <label><input type="checkbox" value="item3"> Item 3</label> </div> </div> `; } // Add Section functionality (using event delegation for dynamic elements) document.getElementById('categories-container').addEventListener('click', (e) => { if (e.target.classList.contains('add-section-btn')) { const categoryBox = e.target.closest('.category-box'); let currentCount = parseInt(categoryBox.getAttribute('data-section-count')); currentCount++; // Increment the count for this specific category // Add the new section const newSection = buildSection(currentCount); categoryBox.insertAdjacentHTML('beforeend', newSection); // Update the data attribute with the new count categoryBox.setAttribute('data-section-count', currentCount.toString()); } });
How This Works:
- Each category box gets its own
data-section-countattribute that starts at 1 (since the first section is Section 1). - When you click "Add Section" inside a category, we find the closest parent category box, grab its current count, increment it, and use that number for the new section.
- We then update the
data-section-countattribute so the next add uses the correct number.
2. Implementing the Save Button Functionality
We need to loop through each category box, collect its title (from the input) and all selected checkbox values, then bundle that data into a usable format (like an array of objects).
Add This JavaScript for the Save Button:
document.getElementById('save-btn').addEventListener('click', () => { const categoryData = []; const allCategoryBoxes = document.querySelectorAll('.category-box'); allCategoryBoxes.forEach(box => { // Get category title const title = box.querySelector('.category-title').value.trim(); // Get selected checkboxes const selectedItems = Array.from(box.querySelectorAll('.checkbox-group input:checked')) .map(checkbox => checkbox.value); // Add to data array (only if title exists, or remove this check if you want empty titles) if (title) { categoryData.push({ categoryTitle: title, selectedItems: selectedItems }); } }); // Now you can use this data! Log it, send it to an API, etc. console.log('Saved Category Data:', categoryData); // Example: Alert the data for testing alert(JSON.stringify(categoryData, null, 2)); });
What This Does:
- Loops through every category box on the page.
- For each box, it grabs the input's value (the category name) and collects all checked checkboxes' values.
- Puts all this into an array of objects, which you can then log, save to local storage, or send to a backend API.
Final Notes
- Make sure your CSS classes (
.category-box,.section-group, etc.) match what you're using in your actual code. - If you want to allow empty category titles, just remove the
if (title)check in the Save function. - The
buildSectionhelper keeps your code DRY (Don't Repeat Yourself) by reusing the section HTML whenever you need to create a new one.
内容的提问来源于stack exchange,提问作者crazydev

