使用getElementsByTagName无法获取新增输入框值的JS作业求助
Hey there! I totally get how frustrating it is when you're stuck on a school assignment for a week—especially as a new learner. Let's break down what's going wrong with your code and fix it step by step.
First, let's identify the key issues in your current code:
- You're trying to get
valuefrom an entire element collection, not individual inputs:document.getElementsByTagName("INPUT").valuedoesn't work because this method returns a group of elements, not a single one. You need to access each element in the collection witharr[i].value. - You're modifying the DOM element collection directly:
arr[i] = parseInt(ar);tries to overwrite a DOM element with a number, which isn't what you want. Instead, you should collect values into a separate variable or add them to the sum as you go. sumisn't initialized: When you dosum = sum + arr[i],sumstarts asundefined, so the result will beNaN(Not a Number). You need to setsum = 0at the start.- You're including the original
input1in the sum: The collection fromgetElementsByTagNameincludes the first input box where you enter the number of inputs to create. We need to skip this one to only sum the new inputs you generated. - No input type restriction: Adding
type="number"to your created inputs will help users enter only numbers and make parsing easier.
Here's the fixed version of your code with clear explanations:
HTML
<input id="input1" type="number" placeholder="Enter number of inputs"><br> <button onclick="myFunction()">dodaj</button> <button onclick="myFunction2()">saberi</button><br> <p id="test"></p>
- Added
type="number"to the first input to enforce numeric input, plus a placeholder for clarity.
JavaScript
function myFunction() { var count = document.getElementById("input1").value; // Optional: Clear existing dynamic inputs first so you don't stack new ones on old var existingInputs = document.querySelectorAll('.dynamic-input'); existingInputs.forEach(input => input.remove()); for (var j = 1; j <= count; j++) { var inp = document.createElement("INPUT"); inp.type = "number"; // Restrict to numeric input inp.className = "dynamic-input"; // Add a class to easily identify our created inputs document.body.appendChild(inp); } } function myFunction2() { var sum = 0; // Initialize sum to a valid number // Get only the inputs we created using the class we added var dynamicInputs = document.querySelectorAll('.dynamic-input'); dynamicInputs.forEach(input => { // Parse value, default to 0 if input is empty or not a number var value = parseInt(input.value) || 0; sum += value; }); document.getElementById("test").innerHTML = "Total sum: " + sum; }
Key improvements explained:
- Added a
dynamic-inputclass to generated inputs: This lets us select only the inputs we created, instead of every input on the page (which included the original count input). No more messy skipping logic! - Initialized
sumto 0: Ensures we start with a valid number instead ofundefined. - Handled empty/invalid values:
parseInt(input.value) || 0treats empty or non-numeric inputs as 0, so your sum won't break if someone leaves an input blank. - Enforced numeric inputs: All inputs now use
type="number", so users can't enter text, reducing parsing issues. - Optional input clearing: The code removes old dynamic inputs before adding new ones—if you want to keep stacking inputs instead, just delete that section.
You've got this—learning JavaScript is tricky at first, but breaking down problems like this is how you build solid skills. Let me know if you have any other questions!
内容的提问来源于stack exchange,提问作者Draza
相关产品推荐
相关产品推荐

