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

为何将number input值赋值给变量后,变量显示为undefined?

Fix: Getting undefined When Trying to Fetch Input's Default Value

Hey there! Let's break down why your quantity variable is returning undefined and how to fix it quickly.

The Root Cause

Your current code uses document.getElementsByClassName("quantity")[0] to target the <td> element (since that's where the quantity class is applied). But <td> elements don't have a value property—the value belongs to the <input> inside the td. So when you try to read .value from the td, you get undefined because that property doesn't exist on it.

Quick Solutions

Here are two straightforward ways to fix this:

Solution 1: Target the Input Directly (No HTML Changes)

Keep your HTML as-is, but adjust your JS to select the <input> inside the .quantity td using querySelector:

var quantity = 0; 
function addItem(){ 
  // Grab the td, then find its child input
  const quantityContainer = document.getElementsByClassName("quantity")[0];
  quantity = quantityContainer.querySelector('input').value;
  // Optional: Convert to number if you need numeric value
  // quantity = Number(quantityContainer.querySelector('input').value);
  console.log(quantity); // Will log "1" (or 1 if converted)
}

Solution 2: Add a Class to the Input (Cleaner for Multiple Inputs)

Modify your HTML to add a class directly to the input, then target that class in JS:

<td class="quantity"> 
  <input class="quantity-input" value="1" type="number"> 
</td>
var quantity = 0; 
function addItem(){ 
  quantity = document.getElementsByClassName("quantity-input")[0].value;
  // Again, convert to number if needed: quantity = Number(quantity);
  console.log(quantity);
}

Bonus Tip

If you only have one such input, using an id instead of a class can be even more straightforward (since getElementById is faster and avoids dealing with collections):

<td class="quantity"> 
  <input id="item-quantity" value="1" type="number"> 
</td>
var quantity = 0; 
function addItem(){ 
  quantity = document.getElementById("item-quantity").value;
  console.log(quantity);
}

内容的提问来源于stack exchange,提问作者billynotreally

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 07:24:18