HTML+JS表单求助:仅能显示FirstName,其余字段无法输出至textarea
Hey there! Let's sort out why only your First Name is showing up in the results textarea. The core issue is that your current SortNames() function only pulls data from the First Name input—you're not grabbing values from the Last Name, CRN, or Professor fields at all. Here's how to fix this:
What's Wrong with the Original Code?
Your existing JavaScript only targets the firstn input and adds that single value to the array. All other fields are completely ignored, so they never make it into the results box.
Updated Solution
First, let's revise the JavaScript to collect all four fields, combine them into a single entry, then add that entry to your array. This way each submission will show a full set of information in the textarea.
Modified JavaScript
// Initialize counter and array var numbernames = 0; var names = new Array(); function SortNames() { // Get values from ALL input fields const firstName = document.theform["firstn"].value; const lastName = document.theform["lastn"].value; const crn = document.theform["crn"].value; const professor = document.theform["prof"].value; // Combine all fields into a single formatted string const fullEntry = `First Name: ${firstName} Last Name: ${lastName} CRN: ${crn} Professor: ${professor} ---`; // Add a divider for readability // Add the full entry to the array names[numbernames] = fullEntry; numbernames++; // Update the textarea with all entries document.theform.sorted.value = names.join("\n"); }
Updated HTML (formatted for readability)
<form name="theform"> <p>First Name: <input type="text" name="firstn" size="10" /></p> <p>Last Name: <input type="text" name="lastn" size="10" /></p> <p>CRN: <input type="text" name="crn" size="10" /></p> <p>Professor: <input type="text" name="prof" size="10" /></p> <input type="button" name="addname" value="Submit" onclick="SortNames();"> <h2>Results:</h2> <textarea cols="50" rows="10" name="sorted"></textarea> </form>
Key Changes Explained
- Collect all field values: We now grab data from
firstn,lastn,crn, andprofinputs instead of just one. - Format the entry: Using template literals (backticks
`), we create a clean, readable string that shows each field's label and value. A divider (---) is added to separate multiple submissions. - Update the array: Each array element now holds a complete set of information instead of just a single name, so when we join the array into the textarea, all fields are displayed.
Try running this updated code—each time you click Submit, the full set of your input will appear in the results box!
内容的提问来源于stack exchange,提问作者Aaron Aguilar

