0

When a user inputs the name of the players, I want my code to separate each player into a different object in my array. My code detects when commas "," are part of the text, but how can I use those commas "," to separate each player name into an individual object in my array.

var subject = [];

function addSubjects() {
namesInputted = document.getElementById('namesInputter').value;

  if (namesInputted.includes(',') == true){
    //HERE IS THE CODE I AM MISSING!!!
  }else{
  subject.push(namesInputted);
  document.getElementById('namesInputter').value = null;
  console.log(subject);
  }
}
  <div class="col-sm-5">
    <h1>RETOS LOCOS</h1>
    <input autocomplete="off" class="form-control" type="text" id="namesInputter" placeholder="Player Name" value="">
    <button type="button" class="btn btn-primary" id="addSubjectsButton" onclick="addSubjects()">Add Player</button>
    <button type="button" class="btn btn-primary" id="startGameButton" onclick="startGame()">Start Game</button>
    </div>
Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
  • Yes it does. What should I do if a question answers my question already? –  Oct 06 '20 at 19:58
  • It should prompt you to accept the duplicate question; if not, just wait, others will come along and vote the same way. – Heretic Monkey Oct 06 '20 at 20:00

2 Answers2

0

Then you should use the split function:

if (namesInputted.includes(',') == true) {
  namesInputted.split(",").forEach(function(name) {
    subject.push(name);
    console.log(name);
  });
  document.getElementById('namesInputter').value = null;
}
BNilsou
  • 886
  • 8
  • 22
0

You need to split your string by commas into an array. Then you iterate each element and you push() it into your array. I also trimmed each result before appending it to get rid of any whitespaces in between.

var subject = [];

function addSubjects() {
namesInputted = document.getElementById('namesInputter').value;

  if (namesInputted.includes(',') == true){
    namesInputted.split( ',' ).forEach( function( item ) {
      subject.push( item.trim() );
    } );
    console.log(subject);
  }else{
  subject.push(namesInputted);
  document.getElementById('namesInputter').value = null;
  console.log(subject);
  }
}
<div class="col-sm-5">
    <h1>RETOS LOCOS</h1>
    <input autocomplete="off" class="form-control" type="text" id="namesInputter" placeholder="Player Name" value="">
    <button type="button" class="btn btn-primary" id="addSubjectsButton" onclick="addSubjects()">Add Player</button>
    <button type="button" class="btn btn-primary" id="startGameButton" onclick="startGame()">Start Game</button>
    </div>
vmank
  • 773
  • 2
  • 7
  • 22