0

I am trying to create an array where users enters multiple items into text box. All i can get my function to return is the first entry. Maybe i am approaching this wrong?

function treez() {
  var treesArray = [];
  var ar = treesArray.push(document.getElementById("trees").value);
  var st = treesArray.toString();
  document.getElementById("tresult").innerHTML = st;

}
Enter 7 Trees
<br>
<textarea rows="5" cols="50" id="trees" name "trees"></textarea>
<br>
<br>
<button type="button" class="processButton" onclick="treez()">submit</button>
<br>
<p id="tresult">
  <p>

2
  • 1
    How can you enter multiple items through single text box?? Commented Dec 9, 2015 at 13:54
  • I have the same doubt. If you want to do it with only one textarea or textbox, first you need to define which is your word separator, it can be a comma or just spaces (not recommended). Commented Dec 9, 2015 at 14:00

2 Answers 2

1

Move treesArray out of the trees function.

With it being in there, its being recreated every call.

var treesArray = [];
function treez() {
  var ar = treesArray.push(document.getElementById("trees").value);
  var st = treesArray.toString();
  document.getElementById("tresult").innerHTML = st;
}
Enter 7 Trees
<br>
<textarea rows="5" cols="50" id="trees" name "trees"></textarea>
<br>
<br>
<button type="button" class="processButton" onclick="treez()">submit</button>
<br>
<p id="tresult">
  <p>

Sign up to request clarification or add additional context in comments.

Comments

0

You can do it like this, asking the user to separate each entry with a comma:

var treesArray = []
function treez() {
    var trees = document.getElementById("trees").value;
    treesArray = trees.split(",");
    document.getElementByID("tresult").innerHTML = treesArray + 
       "   " +  treesArray.join(" - ");
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.