简体   繁体   中英

How to hold a value and pass it while creating dynamic textbox on html/javascript

Im doing a dynamic text box with javascript. But when I execute my button, the value I alredy inserted are erased. So like if I have one textbox and type something on it, when I execute the button to create another textbox it erase all I had type on the 1st one, and create the other one. I understand why it is happening, but I dont know if there is a way to hold the value, and pass to the "new" div.

    <script language="javascript">
var x = 1;
function Button()
{
my_div.innerHTML = my_div.innerHTML +"<label for='variation'>Carro " + x +": </label>" + "<input type='text' name='xcar"+ x +"'>"
x++;
}
</script>

So the problem as I said before was that the my_div.innterHTML was replacing himself and losing the values.

<script language="javascript">
window.onload = function  () {
  
  var createTextbox = function () {
    var x = 1,
        container = document.getElementById('my_div');
      
    return function () {
      var div = document.createElement('div');
          input = document.createElement('input');
      input.type= "text";
      input.name = "xtext" + x;
      div.appendChild(input);
      container.appendChild(div);
      x++;
    }
  }();

  document.getElementById('createButton').onclick = createTextbox;
</script>

<input class="carbutton" type="button" value="+ Carro" id="createButton">

I just used this code instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM