George
George

Reputation: 53

JavaScript store user input in an array on button click

<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>

I need to take input from the user, when user clicks on the Add button after entering data in the Textbox. User may add 'n' number of inputs which I do not know. I need to store the inputs in an array and display it on clicking the Display button. How should that be done? I tried using push(), however it doesn't work:

function addRecord()
{   
    
    var add= document.getElementById("add");
    var addArray= [];
    addArray.push(add.value);
}

Upvotes: 1

Views: 15957

Answers (2)

marmeladze
marmeladze

Reputation: 6564

a spaghetti solution might be as below snippet,

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>

Upvotes: 6

zhuravlyov
zhuravlyov

Reputation: 503

"use strict";

let addButton = document.querySelector('#add');
let displayButton = document.querySelector('#display');
let records = [];

addButton.addEventListener('click', addRecord);
displayButton.addEventListener('click', displayAll);

function addRecord() {
    let record = document.querySelector('#inputtext').value;

    if (!record) {
        return;
    }

    records.push(record);
    document.querySelector('#inputtext').value = '';
}

function displayAll() {
    alert(records);
}
<table>
    <tr>
        <td>Enter the Input</td>
        <td><input type="text" id="inputtext" /></td>
    </tr>
    <tr>
        <td></td>
        <td><button type="button" id="add">Add </button>
            <button type="button" id="display">Display</button>
        </td>
    </tr>
</table>

Upvotes: 1

Related Questions