JS函数失效求助:script.js引入HTML后功能异常排查
Hey there! Let's walk through the issues with your code step by step to get those functions working properly.
1. Missing jQuery Dependency
Your script.js uses $(document).ready(), which is a jQuery-specific function—but you haven't included the jQuery library in your HTML. Without it, the browser doesn't recognize $, so the code inside that ready block will throw an error, and it might even block other parts of your script from running.
Fix: Add the jQuery library before your script.js in userinfo.html:
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script> <script src="script.js"></script>
(If you prefer a local copy, download jQuery and link to the local file instead of the CDN.)
2. Script Placement (Best Practice)
Right now your script is loaded at the top of the <body>. While the onsubmit handler will wait until the form exists, moving scripts to the end of the <body> (right before </body>) ensures all DOM elements are fully rendered before your code runs, avoiding potential element-selection errors.
3. Typo in validateUserInfo()
In the first check for a missing full name, you tried to focus on document.checkoutForm.cardNumber—but checkoutForm doesn't exist in this HTML file! That's a typo; you should target the fullname input in the userInfo form instead:
if (document.userInfo.fullname.value == "") { alert("Please provide full name"); document.userInfo.fullname.focus(); // Fixed this line return false; }
4. Phone Input Type Mismatch
Your phone input uses type="number", which won't let users enter hyphens (-)—but your required format is 123-456-7890. Switch it to type="text" so users can input the correct format:
<input type="text" minlength="12" maxlength="12" name="phone" placeholder="123-456-7890">
5. Broken Phone Number Validation Logic
Strings in JavaScript are immutable, so your current code that tries to modify phoneID directly (like phoneID[i] = phoneID[i + 1]) won't work. Instead, use replace() to strip hyphens before checking if the remaining characters are numbers:
var phoneID = document.userInfo.phone.value; var cleanPhone = phoneID.replace(/-/g, ""); // Remove all hyphens // Check format and numeric validity if (phoneID === "" || phoneID.length !== 12 || phoneID.charAt(3) !== "-" || phoneID.charAt(7) !== "-" || isNaN(cleanPhone)) { alert("Please provide a phone number in the format 123-456-7890"); document.userInfo.phone.focus(); return false; }
6. Missing Elements for Total Calculations
Your $(document).ready() block tries to update elements with IDs like totalShop and totalTax, but these don't appear in the userinfo.html snippet you shared. Make sure these elements exist in the HTML file where this script is loaded (like your checkout page) to avoid "cannot set innerHTML of null" errors.
7. Missing Zipcode Input & Submit Button
Your validateUserInfo() checks for a zipcode, but there's no corresponding input in your form. Plus, there's no submit button to trigger the validation! I've added both in the modified HTML below.
Modified script.js (Key Fixes Applied)
$(document).ready(function () { var total = 30; var totalTax = total * 0.8; var totalShip = total * 0.3; var totalAll = total + totalTax + totalShip; // Guard clauses to avoid errors if elements don't exist if(document.getElementById("totalShop")) document.getElementById("totalShop").innerHTML = total; if(document.getElementById("totalTax")) document.getElementById("totalTax").innerHTML = totalTax; if(document.getElementById("shipping")) document.getElementById("shipping").innerHTML = totalShip; if(document.getElementById("totalDue")) document.getElementById("totalDue").innerHTML = totalAll; }); function applyActiveCss(id) { for (var i = 0; i < document.links.length; i++) { document.links[i].className = document.links[i].id == id ? 'active' : 'links'; } } function validateCheckout() { if (document.checkoutForm.cardNumber.value == "") { alert("Please provide card number"); document.checkoutForm.cardNumber.focus(); return false; } if (document.checkoutForm.month.value == "" || isNaN(document.checkoutForm.month.value) || document.checkoutForm.month.value.length != 2) { alert("Please provide a valid month (MM)"); document.checkoutForm.month.focus(); return false; } if (document.checkoutForm.year.value == "" || isNaN(document.checkoutForm.year.value) || document.checkoutForm.year.value.length != 4) { alert("Please provide a valid year (YYYY)"); // Fixed typo here document.checkoutForm.year.focus(); return false; } return true; } function validateUserInfo() { if (document.userInfo.fullname.value == "") { alert("Please provide full name"); document.userInfo.fullname.focus(); // Fixed focus target return false; } if (document.userInfo.email.value == "") { alert("Please provide your Email!"); document.userInfo.email.focus(); return false; } var emailID = document.userInfo.email.value; var atpos = emailID.indexOf("@"); var dotpos = emailID.lastIndexOf("."); if (atpos < 1 || (dotpos - atpos < 2)) { alert("Please enter correct email ID"); document.userInfo.email.focus(); return false; } if (document.userInfo.zipcode.value == "" || isNaN(document.userInfo.zipcode.value) || document.userInfo.zipcode.value.length != 5) { alert("Please provide a zip in the format 12345"); document.userInfo.zipcode.focus(); return false; } var phoneID = document.userInfo.phone.value; var cleanPhone = phoneID.replace(/-/g, ""); if (phoneID === "" || phoneID.length !== 12 || phoneID.charAt(3) !== "-" || phoneID.charAt(7) !== "-" || isNaN(cleanPhone)) { alert("Please provide a phone number in the format 123-456-7890"); document.userInfo.phone.focus(); return false; } return true; }
Modified userinfo.html
<!DOCTYPE html> <html lang="en" xmlns="http://www.w3.org/1999/xhtml"> <head> <meta charset="utf-8" /> <title>Personal Information</title> <link rel="stylesheet" type="text/css" href="StyleSheet1.css"> </head> <body> <h1>User Information</h1> <p>Please fill out the following information.</p> <form action="shipinfo.html" name="userInfo" onsubmit="return validateUserInfo();"> <table> <tbody> <tr> <td> Full Name: <br> <input type="text" maxlength="100" name="fullname" required> </td> <td> Phone Number: <br> <input type="text" minlength="12" maxlength="12" name="phone" placeholder="123-456-7890"> </td> </tr> <tr> <td> Address Line 1: <br> <input type="text" maxlength="100" name="add1" required> </td> <td> Address Line 2: <br> <input type="text" maxlength="100" name="add2"> </td> </tr> <tr> <td> City: <br> <input type="text" maxlength="100" name="city" required> </td> <td> Zip Code: <br> <input type="text" maxlength="5" name="zipcode" placeholder="12345"> </td> </tr> </tbody> </table> <button type="submit">Continue to Shipping Info</button> </form> <!-- Load scripts at the end of the body --> <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script> <script src="script.js"></script> </body> </html>
内容的提问来源于stack exchange,提问作者swettums14

