Home > Blockchain >  Avoiding the reset of JS text inputs
Avoiding the reset of JS text inputs

Time:12-06

A bit of an anomaly is showing up in my code. I'm working on a graphing calculator, where it may be necessary for users to enter multiple expressions for evaluation. To do this I have a text input & a button that essentially adds a new input to the parent div each time it is clicked, like this:

document.getElementById("add").onclick =  function(){
  document.getElementById("boxes").innerHTML  = '<br/><input type="text" spellcheck="false" id="b'   nBox  '" />';
}

Whilst this works, the values of previous inputs in the div are being reset each time I press this button. I'm assuming adding to the innerHTML has some sort of clearance effect on other elements in the parent div.

Is there a way I can prevent this?

CodePudding user response:

Altering the innerHTML causes the browser to re-render the entire page and wipes the state in those inputs. appendChild should clean that up:

<button id="add">Add</button>
<div id="boxes"></div>

<script>
document.getElementById("add").onclick =  function(){
  let input = document.createElement('input');
  input.type = "text";
  input.spellcheck="false";
  input.classList = ["eq"];
  document.getElementById("boxes").appendChild(input);
}
</script>

CodePudding user response:

Don't use innerHTML for these things, have a look at Element.appendChild(). In your case, try:

document.getElementById("boxes").appendChild('<br/><input type="text" spellcheck="false" id="b'   nBox  '" />');

Please also have a look at .createElement() for cleaner code.

  • Related