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

JavaScript按钮点击获取Div内输入框值的技术问题咨询

Fixing Duplicate ID Issue in Your Input/Button Setup

Hey there! Let's break down why your current code isn't behaving as expected, and walk through straightforward fixes.

The Core Problem

The main issue here is duplicate id attributes in your HTML. By HTML standards, id values must be unique across the entire document. When you call document.getElementById("value"), it will always return the first element matching that id—so no matter which button you click, you'll only ever get the value of the first "banana" input.

Solution 1: Use Classes + Pass Button Reference

A simple, direct fix is to replace the duplicate ids with a class, then pass the clicked button to your function so it can target the input in the same container.

Updated HTML:

<div class="test">
  <input class="value-input" type="text" name="" value="banana">
  <button type="button" name="button" onclick="myfunction(this)">Button</button>
</div>
<div class="test">
  <input class="value-input" type="text" name="" value="apple">
  <button type="button" name="button" onclick="myfunction(this)">Button</button>
</div>

Updated JavaScript:

function myfunction(button) {
  // Traverse to the parent .test div, then grab the input inside it
  const input = button.parentElement.querySelector('.value-input');
  const value = input.value;
  alert(value);
}

Solution 2: Event Delegation (Cleaner & Scalable)

If you want to avoid inline onclick attributes (a best practice for maintainability), use event delegation. This lets you attach one single event listener to a parent container, instead of one per button.

Updated HTML (no inline onclick):

<div class="test-group">
  <div class="test">
    <input class="value-input" type="text" name="" value="banana">
    <button type="button" name="button">Button</button>
  </div>
  <div class="test">
    <input class="value-input" type="text" name="" value="apple">
    <button type="button" name="button">Button</button>
  </div>
</div>

Updated JavaScript:

// Attach listener to the parent container
document.querySelector('.test-group').addEventListener('click', function(e) {
  // Check if the clicked element is a button
  if (e.target.tagName === 'BUTTON') {
    // Find the input in the same .test div as the clicked button
    const input = e.target.closest('.test').querySelector('.value-input');
    alert(input.value);
  }
});

Key Takeaways

  • Never reuse id values in HTML—they’re designed to be unique identifiers.
  • Use classes for repeated elements that share behavior or styling.
  • Event delegation is ideal for handling multiple similar elements, especially if you plan to add more dynamically later.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 11:15:07