提交按钮验证失效:输入为milk时无法跳转至下一页
Hey there! Let's work through this conditional redirect problem together. Since your back-to-home button is already working perfectly, we can build on that same navigation logic for the submit button's specific requirement.
The core idea is to listen for the submit button click, check if the input value exactly matches "milk", and then trigger the redirect only when that condition is met. Here's a step-by-step implementation:
Step 1: Example HTML Structure
First, let's assume your page has an input field, submit button, and your existing functional back button. Here's a standard setup you can adapt:
<!-- Input field for user entry --> <input type="text" id="userInput" placeholder="Type here..."> <!-- Submit button we need to add logic to --> <button id="submitBtn">Submit</button> <!-- Your already-working back to home button --> <button id="backToHomeBtn">Back to Home</button>
Step 2: JavaScript Logic for Conditional Redirect
Add this script to handle the submit button's behavior. We'll avoid page refreshes (if using a form) and validate the input value:
// Grab elements from the DOM const submitBtn = document.getElementById('submitBtn'); const userInput = document.getElementById('userInput'); const backBtn = document.getElementById('backToHomeBtn'); // Handle submit button click submitBtn.addEventListener('click', function(e) { // If your input is inside a <form>, uncomment this to stop default page refresh // e.preventDefault(); // Get input value and trim extra whitespace const inputValue = userInput.value.trim(); // Check if input matches "milk" (case-sensitive) if (inputValue === 'milk') { // Redirect to your next page (replace with your actual page path) window.location.href = '/next-page.html'; } else { // Optional: Show feedback if input is incorrect alert('Oops! Please enter "milk" to move to the next page.'); } }); // Your existing back button logic (included for reference since it's already working) backBtn.addEventListener('click', function() { window.location.href = '/home.html'; });
Quick Tips to Adjust the Behavior:
- Case Insensitivity: If you want to accept "Milk", "MILK", or other capitalizations, modify the condition to
inputValue.toLowerCase() === 'milk'. - Form Integration: If your input is wrapped in a
<form>tag, make sure to includee.preventDefault()to prevent the page from reloading before the redirect happens. - Custom URLs: Replace
/next-page.htmland/home.htmlwith your actual page paths (either relative or absolute).
This approach uses the same window.location.href method that's already working for your back button, so it should integrate smoothly with your existing setup.
内容的提问来源于stack exchange,提问作者Ephraim Cohen

