通过JavaScript+PHP向MySQL添值,手风琴按钮值传隐藏表单失败
It sounds like your hidden day input isn't retaining its value when set to type="hidden", even though it works when visible. Let's break down the common causes and fix this step by step.
First, Diagnose the Core Issue
Hidden inputs (type="hidden") should always be submitted with the form regardless of visibility—unless they're disabled or their value isn't properly set before submission. The most likely culprit is that your JavaScript isn't assigning the Day value to the hidden input correctly when the accordion button is clicked, or the assignment happens at the wrong time.
Step-by-Step Fix
1. Ensure Your HTML Structure is Correct
First, store the Day value in an accessible attribute (like data-day) on your accordion button, and make sure the hidden input lives inside the corresponding form:
<!-- Accordion Button with Day value stored in data-day --> <button class="accordion-btn" data-day="1">Day 1</button> <div class="accordion-panel"> <form method="POST" action="save_to_db.php"> <!-- Hidden input for Day value --> <input type="hidden" name="day" id="day-input"> <textarea name="content" placeholder="Enter your text here..."></textarea> <button type="submit">Save</button> </form> </div>
Avoid using style="display:none" on a text input instead of type="hidden"—while it sometimes works, type="hidden" is the standard and more reliable approach for hidden form data.
2. Update JavaScript to Assign Value on Click
The key is to assign the Day value when the accordion button is clicked (and the panel expands). This ensures the hidden input gets the correct value right before the user submits the form.
Vanilla JavaScript Example:
// Target all accordion buttons document.querySelectorAll('.accordion-btn').forEach(button => { button.addEventListener('click', () => { // Get the Day value from the button's data attribute const dayValue = button.getAttribute('data-day'); // Find the hidden input inside the corresponding accordion panel const hiddenInput = button.nextElementSibling.querySelector('#day-input'); if (hiddenInput) { // Assign the Day value to the hidden input hiddenInput.value = dayValue; // Uncomment below to debug and confirm the value is set // console.log('Assigned day value:', hiddenInput.value); } // Toggle the accordion panel visibility (your existing logic) button.nextElementSibling.classList.toggle('active'); }); });
If Using Bootstrap Accordion:
If you're using Bootstrap's collapse component, listen for the show.bs.collapse event to capture when the panel opens:
$('.accordion-collapse').on('show.bs.collapse', function(e) { // Get the trigger button that opened the panel const triggerButton = $(e.relatedTarget); // Extract the Day value from the button's data attribute const dayValue = triggerButton.data('day'); // Assign the value to the hidden input inside the panel $(this).find('input[name="day"]').val(dayValue); });
3. Verify the Value is Set Before Submission
Add a quick debug check to confirm the hidden input has the right value before testing the database save:
- Add an
onsubmithandler to your form:
<form method="POST" action="save_to_db.php" onsubmit="console.log('Day value being submitted:', document.getElementById('day-input').value);">
- Check your browser's developer console when submitting the form—if the value shows up correctly, the issue is likely in your PHP code.
4. Fix Your PHP Database Logic
Ensure your PHP script properly receives and sanitizes the day value (always sanitize to prevent SQL injection):
<?php // Connect to your MySQL database (update credentials as needed) $conn = mysqli_connect('localhost', 'your_username', 'your_password', 'your_database'); if ($_SERVER['REQUEST_METHOD'] === 'POST') { // Sanitize inputs to prevent SQL injection $day = mysqli_real_escape_string($conn, $_POST['day'] ?? ''); $content = mysqli_real_escape_string($conn, $_POST['content'] ?? ''); // Only proceed if both values are present if (!empty($day) && !empty($content)) { $sql = "INSERT INTO your_table_name (day, content) VALUES ('$day', '$content')"; if (mysqli_query($conn, $sql)) { echo "Data saved successfully!"; } else { echo "Error saving data: " . mysqli_error($conn); } } else { echo "Error: Day or content value is missing!"; } } // Close the database connection mysqli_close($conn); ?>
Common Pitfalls to Avoid
- Disabled Inputs: If your hidden input has a
disabledattribute, it won't be submitted with the form—remove this if present. - Incorrect Selector: Double-check that your JavaScript targets the right hidden input (especially with multiple accordion panels). Targeting the input relative to the clicked button is safer than using global selectors.
- Early Assignment: Don't set the hidden input's value on page load—wait until the user clicks the accordion button, since they might switch between panels before submitting.
内容的提问来源于stack exchange,提问作者Alison Persson

