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

JavaScript实现输入框内容变更时同步修改标签文本的问题咨询

Hey there! Let's get your label to sync up with the input box properly. I spot a couple of small tweaks needed in your code—here's how to fix it:

First, fix how you fetch the input content

Your current code uses innerHTML to get the input's text, but for <input> elements, we need to use the value property instead. Inputs store user-entered content in value, while innerHTML is meant for elements with nested content like <div> or <p>.

Second, pick the right event for real-time (or focused) updates

The onchange event only triggers when the input loses focus. If you want the label to update as the user types, pastes, or drags text (real-time sync), use the oninput event—it’s more reliable for all kinds of input changes. If you only want updates when the user finishes typing and moves away from the box, stick with onchange but still fix the value issue.

Corrected code examples:

JavaScript function:

function updateModuleCode() {
  // Grab the input's current value
  var inputText = document.getElementById('txtModCode').value;
  // Update the label with plain text (safer than innerHTML)
  document.getElementById('lblModCode').textContent = inputText;
}

I swapped innerHTML for textContent on the label too—it’s safer because it treats input as plain text, so accidental HTML entries won’t get rendered as markup.

HTML elements (for real-time sync):

<input type="text" name="txtModCode" id="txtModCode" class="form-control" placeholder="Enter Module Code Here" oninput="updateModuleCode()" />
<label id="lblModCode"></label>

For updates only on focus loss:

Just change the input’s event back to onchange="updateModuleCode()"—the rest of the code stays the same.

That should have your label syncing perfectly with the input box. Let me know if you hit any snags!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 03:58:48