您如何将用户输入存储到数组中?

时间:2019-05-03 01:41:08

标签: javascript arrays

如何将来自<input type="text">的用户输入存储到Javascript数组中? 到目前为止,我已经知道了:

<input type="text" id="user_input">
<button type="button>click</button>

<script>
const myArray = [];
//what next? I don't mind using console.log to test
</script>

3 个答案:

答案 0 :(得分:3)

首先,您可以使用<button>中的onclick属性,该属性可以在单击按钮时执行功能。

<button type="button" onclick="addData()">click</button>

在JavaScript上,您将定义addData()函数。

const inputData = [];

const addData = () => {
  const inputText = document.getElementById('user_input');
  inputData.push(inputText.value);
}

这是给您的演示:

<input type="text" id="user_input">
<button type="button" onclick="addData()">click</button>

<script>
const inputData = [];

const addData = () => {
  const inputText = document.getElementById('user_input');
  inputData.push(inputText.value);
  console.log(inputData);
}
</script>

答案 1 :(得分:0)

如果您的问题是关于用户单击按钮时将输入添加到数组中,那么就足够了:

<input type="text" id="user_input">
<button type="button" onclick="storeInput()">store input</button>

<script>
const storedUserInputs = [];
function storeInput() {
  var input = document.getElementById("user_input"); // get reference to the input element
  storedUserInputs.push(input.value); // catpure the value
  input.value = ""; //reset the input value
  console.log(storedUserInputs);
}
</script>

答案 2 :(得分:0)

意大利面条解决方案可能如下段所示,

values = [];

function addRecord() {
  var inp = document.getElementById('inputtext');
  values.push(inp.value);
  inp.value = "";  
}

function displayRecord() {
  document.getElementById("values").innerHTML = values.join(", ");
}
 <table>
            <tr>
                <td>Enter the Input</td>
                <td><input type="text" id="inputtext" /></td>
            </tr>
            <tr>
                <td></td>
                <td><button type="button" id="add" onclick="addRecord();">Add </button>
                <button type="button" id="display" onclick="displayRecord();">Display</button>
                </td>
            </tr>
    </table>

   <div id='values'>
</div>