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

如何将来自的用户输入存储<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>


凤凰求蛊
浏览 177回答 3
3回答

慕桂英4014372

首先,您可以使用中的onclick属性<button>,该属性可以在单击按钮时执行功能。<button type="button" onclick="addData()">click</button>在您的JavaScript上,您将定义addData()函数。const inputData = [];const addData = () => {&nbsp; const inputText = document.getElementById('user_input');&nbsp; inputData.push(inputText.value);}这是给您的演示:<input type="text" id="user_input"><button type="button" onclick="addData()">click</button><script>const inputData = [];const addData = () => {&nbsp; const inputText = document.getElementById('user_input');&nbsp; inputData.push(inputText.value);&nbsp; console.log(inputData);}</script>

温温酱

如果您的问题是关于在用户单击按钮时将输入添加到数组中,那么就足够了:<input type="text" id="user_input"><button type="button" onclick="storeInput()">store input</button><script>const storedUserInputs = [];function storeInput() {&nbsp; var input = document.getElementById("user_input"); // get reference to the input element&nbsp; storedUserInputs.push(input.value); // catpure the value&nbsp; input.value = ""; //reset the input value&nbsp; console.log(storedUserInputs);}</script>

慕雪6442864

意大利面条的解决方案可能如下例所示,values = [];function addRecord() {&nbsp; var inp = document.getElementById('inputtext');&nbsp; values.push(inp.value);&nbsp; inp.value = "";&nbsp;&nbsp;}function displayRecord() {&nbsp; document.getElementById("values").innerHTML = values.join(", ");}&nbsp;<table>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <tr>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <td>Enter the Input</td>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <td><input type="text" id="inputtext" /></td>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </tr>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <tr>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <td></td>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <td><button type="button" id="add" onclick="addRecord();">Add </button>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <button type="button" id="display" onclick="displayRecord();">Display</button>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </td>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </tr>&nbsp; &nbsp; </table>&nbsp; &nbsp;<div id='values'></div>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript