Input not being added to array (beginner) JavaScript Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Input not being added to array (beginner) JavaScript without wasting too much if your time.

The question is published on by Tutorial Guruji team.

When text is written into the input box and then the button is clicked, I want the text (value) to be added to the array I have created for it (the array is called ‘subject’). The text (value) from the input box is not being added… why?

var subject = [];
function addSubjects() {
  namesInputted = document.getElementById('namesInputter').value;
  subject.push(namesInputted);
  console.log(subject);
}
<!DOCTYPE html>
<html lang="en" dir="ltr">

<head>
  <meta charset="utf-8">
  <title>Prueva tu Suerte</title>
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">
  <link rel="stylesheet" href="styles.css">
</head>

<body>
  <form class="" action="index.html" method="post">
    <input type="text" id="namesInputter" value="">
    <button onclick="addSubjects()">Add Player</button>
  </form>
  <span id='S'></span>
  <span id='V'></span>
  <span id='O'></span>
  <span id='P'></span>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  <script src="function.js"></script>
</body>

</html>

Answer

Actually, You code is working. The input value is appending to the array. But the Issue is, You are using form. So when you click the button, It will submit the form right after add the value to array. So page will refresh and the array will become empty.

Just remove form tag, if you don’t want to submit data.

var subject = [];
function addSubjects() {
  namesInputted = document.getElementById('namesInputter').value;
  subject.push(namesInputted);
  console.log(subject);
}
<!DOCTYPE html>
<html lang="en" dir="ltr">

<head>
  <meta charset="utf-8">
  <title>Prueva tu Suerte</title>
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">
  <link rel="stylesheet" href="styles.css">
</head>

<body>
  <input type="text" id="namesInputter" value="">
  <button onclick="addSubjects()">Add Player</button>
  <span id='S'></span>
  <span id='V'></span>
  <span id='O'></span>
  <span id='P'></span>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  <script src="function.js"></script>
</body>

</html>
We are here to answer your question about Input not being added to array (beginner) JavaScript - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji