首页 > 解决方案 > 无法从 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()函数没有返回输入框的新值。我知道这是非常基本的,但它不适合我。你能帮我弄清楚这里出了什么问题吗?提前致谢 :)

标签: javascripthtml

解决方案


有点不清楚你想要什么。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 问题。您是否简化了您的问题,希望得到一个可能帮助您解决有关其他/更多问题的答案?


推荐阅读