You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用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 value from an entire element collection, not individual inputs: document.getElementsByTagName("INPUT").value doesn't work because this method returns a group of elements, not a single one. You need to access each element in the collection with arr[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.
  • sum isn't initialized: When you do sum = sum + arr[i], sum starts as undefined, so the result will be NaN (Not a Number). You need to set sum = 0 at the start.
  • You're including the original input1 in the sum: The collection from getElementsByTagName includes 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:

  1. Added a dynamic-input class 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!
  2. Initialized sum to 0: Ensures we start with a valid number instead of undefined.
  3. Handled empty/invalid values: parseInt(input.value) || 0 treats empty or non-numeric inputs as 0, so your sum won't break if someone leaves an input blank.
  4. Enforced numeric inputs: All inputs now use type="number", so users can't enter text, reducing parsing issues.
  5. 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 08:03:01