如何通过JavaScript基于select标签跳转页面并设置统一账号密码?
Got it, let's put this together for you. You need two key things here: a username/password check (both locked to admin), and the select dropdown navigation you already started building. Here's a complete, working implementation that ties both together smoothly:
HTML Code
<!-- Authentication Inputs --> <div class="auth-section"> <label for="username">Username:</label> <input type="text" id="username" placeholder="Enter username"> </div> <div class="auth-section"> <label for="password">Password:</label> <input type="password" id="password" placeholder="Enter password"> </div> <!-- Building Selection Dropdown --> <select id="mySelect"> <option value="">Choose a Building</option> <option>Building 1</option> <option>Building 2</option> <option>Building 3</option> </select> <!-- Trigger Button --> <button onclick="myFunction()">Navigate to Building</button>
JavaScript Code
function myFunction() { // Step 1: Grab and validate credentials first const username = document.getElementById("username").value.trim(); const password = document.getElementById("password").value.trim(); if (username !== "admin" || password !== "admin") { alert("Oops! Invalid credentials. Use 'admin' for both username and password."); return; // Halt execution if auth fails } // Step 2: Handle building navigation const selectElement = document.getElementById("mySelect"); const selectedBuilding = selectElement.options[selectElement.selectedIndex].text; switch(selectedBuilding) { case "Building 1": window.location.href = "../../realview/Building1/"; break; case "Building 2": window.location.href = "../../realview/Building2/"; break; case "Building 3": window.location.href = "../../realview/Building3/"; // Fill in your target path here break; default: alert("Please pick a valid building from the dropdown first!"); } }
Quick Breakdown:
- Auth First: We prioritize checking credentials before any navigation logic—if the user enters anything other than admin for both fields, they get an alert and the function stops.
- Cleaner Navigation: Swapped your chain of
else ifstatements for aswitchblock, which is easier to maintain if you add more buildings later. - User Feedback: Added alerts for empty selections or invalid logins so users always know why something isn't working.
内容的提问来源于stack exchange,提问作者Mohamed Magdy
相关产品推荐
相关产品推荐

