Bootstrap导航标签跳转后移除哈希及表单选项默认值设置问题
Solution
1. Remove URL Hash After Tab Navigation
After showing the target Bootstrap tab, use history.replaceState() to update the URL without the hash—this avoids page reloads while cleaning up the address bar.
// Handle hash-based tab navigation on page load const hash = window.location.hash; if (hash) { const tabElement = document.querySelector(hash); if (tabElement) { const bsTab = new bootstrap.Tab(tabElement); bsTab.show(); // Remove hash from URL without reloading the page history.replaceState(null, document.title, window.location.pathname + window.location.search); } }
2. Fix Form Selection Logic
Use Bootstrap's shown.bs.tab event to set the form's select value only when the form tab is displayed. This ensures consistent behavior whether the user arrives via the button, direct link, or tab click.
Update the Redirect Function
Set localStorage before navigating to ensure the value is available on the new page load:
function redirectToForm() { localStorage.setItem("selectedOption", "2"); window.location.href = "http://www.example.com/#nav-contact-me-tab"; }
Add Tab Show Event Listener
This listener handles setting the select value every time the form tab is activated:
// Handle form selection when the contact tab is shown document.addEventListener('shown.bs.tab', function (event) { const reasonSelect = document.getElementById("reason"); if (!reasonSelect) return; // Exit if the select element doesn't exist if (event.target.id === 'nav-contact-me-tab') { const selectedOption = localStorage.getItem("selectedOption"); if (selectedOption) { reasonSelect.value = selectedOption; localStorage.removeItem("selectedOption"); // Clear after use } else { reasonSelect.value = "0"; // Default to disabled option } } });
Button Code (Unchanged)
<button id="gotoformselect2" onclick="redirectToForm()">Request References</button>
Key Improvements
- Consistent Default Behavior: Every time the form tab is shown without a
selectedOptionin localStorage, it defaults to the disabled option "0". - One-Time Use of localStorage: The stored value is cleared immediately after setting the select, preventing it from affecting future visits.
- Tab Activation Awareness: Only modifies the form when the form tab is active, avoiding unintended changes on other tabs.
内容的提问来源于stack exchange,提问作者The Digital Guru
相关产品推荐
相关产品推荐

