0

i've been trying to make a list of names. the names are inputed by enter click. after that it should fill an array which later will be used to shuffle them. as the enter is clicked im trying to add each array child to a styled div.

that's what i tryed so far -

var values = [];
document.getElementById("inputtext").onkeypress = function(event){
  if (event.keyCode == 13 || event.which == 13){
    var inp = document.getElementById('inputtext');
    values.push(inp.value);
    inp.value = "";
    for(var i = 0; i < values.length; i += 1) {
      var udiv = document.createElement("div");
      udiv.className = "idiv";
      udiv.innerHTML = document.getElementById("inputtext").value;
      document.getElementsByClassName('addednames')[0].appendChild(udiv);
    }
  }
}

i'm not sure that's even the right way hope for more guidance. thanks in advance

Mamun
  • 66,969
  • 9
  • 47
  • 59
Tal Sluk
  • 23
  • 2

2 Answers2

1

With inp.value = "" you are re-setting the input's value but you are trying to access the value inside the loop. Instead, you can use the array value to create the element:

var values = [];
document.getElementById("inputtext").onkeypress = function(event){
  if (event.keyCode == 13 || event.which == 13){
    document.getElementsByClassName('addednames')[0].innerHTML = ''; //Clear the previously created div
    var inp = document.getElementById('inputtext');
    values.push(inp.value);
    inp.value = ""; 
    values.sort(() => Math.random() - 0.5); //shuffle the array
    for(var i = 0; i < values.length; i += 1) {
      var udiv = document.createElement("div");
      udiv.className = "idiv";
      udiv.innerHTML = values[i];
      document.getElementsByClassName('addednames')[0].appendChild(udiv);
    }
  }
}
.idiv{
  border: 1px solid lightgray;
  margin: 3px 0;
  padding: 5px;
}
<input id="inputtext"/>
<div class="addednames"></div>
Mamun
  • 66,969
  • 9
  • 47
  • 59
0

There are a few minor issues with your code:

-The for loop. What it'd do is every time you enter a new input, you'll get all the previous inputs appended to the div.

-Using a className to access an element. Why don't you just use an ID instead? That'd eliminate potential issues in the future if you decided to add more elements with that same class.

-Using the var keyword. Try using let instead. Here's a good post on the reason why: What's the difference between using "let" and "var"?

Other than that it's all good.

Thomas Bui
  • 188
  • 3
  • 10