javascript - 无法从 HTML 的输入框中获取新键入的值
问题描述
我有一个包含两个输入框和一个按钮的表格行。单击该按钮时,我需要获取用户在输入框中键入的新键入的值。所以我正在这样做。
<tr>
<!-- Input box row (for new row input) -->
<td><input type="text" id="new_E" value="Enter new text"></td>
<td><input type="text" id="new_I" value="Enter new text"></td>
<td><button class="add" onclick="add_row()">Add row</button></td>
</tr>
add_row()
函数如下所示:
function add_row()
{
//Step 1: Getting what the user typed in the new row
var new_E=document.getElementById("new_E").value;
var new_I=document.getElementById("new_I").value;
console.log("User typed this:"+ new_E);
}
现在,在输入框中也输入了一个新值之后,这就是我在控制台中看到的:
User typed this: Enter new text
我无法弄清楚为什么document.getElementById("new_E").value
内部add_row()
函数没有返回输入框的新值。我知道这是非常基本的,但它不适合我。你能帮我弄清楚这里出了什么问题吗?提前致谢 :)
解决方案
有点不清楚你想要什么。new_I 似乎是您的“新文本”,对吗?所以这首先应该是控制台日志记录而不是“ new_E”。
您还有一些我想指出的其他事情。您手动设置这些值。使用占位符属性代替您在此处执行的操作。
function add_row()
{
//Step 1: Getting what the user typed in the new row
var new_E=document.getElementById("new_E").value;
var new_I=document.getElementById("new_I").value;
console.log("User typed this: "+ new_E+", in the first input field");
console.log("User typed this: "+ new_I+", in the second input field");
}
<input type="text" id="new_E" placeholder="Enter new text" value="test1">
<input type="text" id="new_I" placeholder="Enter new text" value="test2">
<button class="add" onclick="add_row()">Add row</button>
如果您的意思是将“新”值与旧值连接起来,以便它们出现在同一个控制台日志中,您可以执行以下操作:
function add_row()
{
//Step 1: Getting what the user typed in the new row
var new_E=document.getElementById("new_E").value;
var new_I=document.getElementById("new_I").value;
console.log("User typed this: "+ new_E+" "+new_I);
}
<input type="text" id="new_E" placeholder="Enter new text" value="test1">
<input type="text" id="new_I" placeholder="Enter new text" value="test2">
<button class="add" onclick="add_row()">Add row</button>
这可能是XY 问题。您是否简化了您的问题,希望得到一个可能帮助您解决有关其他/更多问题的答案?
推荐阅读
- c# - 获取布尔值作为字符串
- java - 使用反应式 Java,仅当通量为空时才插入元素
- python - 这里有什么不同?我只是不支持它
- javascript - Javascript弹出窗口?
- visual-studio - 在 .Net 5 上使用 EnvDTE CodeModel 进行重构
- c# - 如何从子实体框架核心获取数据?
- r - 将分析输出添加到 df 的 Purr 映射
- javascript - Firestore 查询返回未定义的快照(Vue.js / Firestore / Vuefire)
- discord - 发送前缀时发送消息 discord.py
- r - 如何在不使用 for 循环的情况下使用 str_split 拆分嵌套列表?