Home > Back-end >  Add items from HTML input to an empty array in JavaScript
Add items from HTML input to an empty array in JavaScript

Time:06-16

I am trying to populate a blank Javascript array with usernames inputted from a single HTML input field (input example: bill, bob, jim) but I can't get it working the way I want. The HTML code I'm using is:

<input id="users" type="text" placeholder="Enter Users">
<button  onclick="addTo()">Click to add names</button>

And the JavaScript I have so far is

let myarray = []

function addTo() {
  myarray.push(document.getElementById("users").value)
    }

The inputted data does get pushed to the array, but it gets populated as 1 single item

['bill, bob, jim']

but what I want is for it to be submitted as 3 separate items so I can access them via the index such as myarray[1]

['bill', 'bob', 'jim']

Does anyone know how I can change the code to achieve this? All of the names have to be inputted via the single HTML input field.

CodePudding user response:

Use

myarray.push(...document.getElementById("users").value.split(','))

CodePudding user response:

The missing part is: Splitting the captured string.

Embrace the function EventTarget.addEventListener for binding a event to an element in the DOM.

const myarray = [],
      userInput = document.querySelector("#users");

document.querySelector("#btn").addEventListener("click", (e) => {
  e.preventDefault();
  myarray.push(...userInput.value.split(",").map(s => s.trim()));
  
  console.log(myarray);
});
<input id="users" type="text" placeholder="Enter Users">
<button id="btn" >Click to add names</button>

  • Related