首页 > 解决方案 > How would I select an input from a form and store it in a variable?

问题描述

For example, if i had a form like this:

<form id="form1">
  <input type="text" name="item">
</form>
<button onclick="outputItem"></button>

How would I output the input from the form?

标签: javascripthtml

解决方案


您可以编写一个函数,您可以在其中使用querySelector()获取元素来获取输入的值:

function outputItem(){
  var v = document.querySelector('#form1 > input[name=item]').value;
  console.log(v);
}
<form id="form1">
  <input type="text" name="item">
</form>
<button onclick="outputItem()">Print</button>


推荐阅读