Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

190
Views
Add items from HTML input to an empty array in JavaScript

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 class="btn" 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.

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

Use:

myarray.push(...document.getElementById("users").value.split(','))
about 4 years ago · Juan Pablo Isaza Report

0

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" class="btn">Click to add names</button>

about 4 years ago · Juan Pablo Isaza Report

0

Observations :

  • If user enter same name multiple times, Are we going to accept those or we are going to discard duplicates ?
  • Are we storing all the names user enter on pressing Click to add names button ?

As per the consideration of above two points. Here is the demo :

let myarray = []

function addTo() {
  myarray.push(...document.getElementById("users").value.split(','));
  console.log([...new Set(myarray)]);
}
<input id="users" type="text" placeholder="Enter Users">
<button class="btn" onclick="addTo()">Click to add names</button>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!