0

I need to know how to add the character a user pressed to a variable without erasing the variables previous data. For example, when a user types a it adds a to a variable. Then the user types t and it adds t to the variable, but it saves the a, so now the variable is a string containing at. I have tried for quite awhile now and still can not figure out how to do this.

HittmanA
  • 293
  • 1
  • 4
  • 11
  • You are talking about arrays. – SaidbakR Apr 27 '16 at 22:37
  • @sємsєм No because if you try to display the array with `document.getElementById('demo').innerHTML = your_array;` it displays it like this: `a,t,etc.,` – HittmanA Apr 27 '16 at 22:39
  • Sorry, I don't, clearly, understand your last comment. However, your question is the definition of an array. – SaidbakR Apr 27 '16 at 22:39
  • @sємsєм The comment sent early sorry for that. – HittmanA Apr 27 '16 at 22:40
  • I think he means something more like `var = var + 'a'` – P3t3r6 Apr 27 '16 at 22:41
  • You have to make `your_array` as a concatenated string which gets its value from a `loop` through the array. – SaidbakR Apr 27 '16 at 22:41
  • @HittmanA can you add some additional info? Maybe some code of what you have tried already? Also how these users add characters, from and input field or by clicking buttons, or something else? – pizzarob Apr 27 '16 at 23:14

1 Answers1

0

You can utilize oninput event, create a variable that is undefined, at first input event, set window[variable] and created variable to character user input; at subsequent input from user, concatenate window[variable] from last character at user input using String.prototype.slice() with parameter -1

var q = void 0;

document.querySelector("input").oninput = function(e) {
  if (!q && !window[e.target.value]) {
    window[e.target.value] = q = e.target.value;
  } else {
    window[q] += e.target.value.slice(-1);
    console.log(window[q])
  }
}
<input type="text" />
guest271314
  • 1
  • 15
  • 104
  • 177