Search code examples
javascripthtmlstring-concatenation

Javascript concat clearing input fields


function js() {
  document.getElementById("example").innerHTML = document.getElementById("example").innerHTML+"<input type=\"text\" name=\"name\" />";
}
<div id="example">
  <input type="text" name="name[]" />
</div>

<button type="button" onclick="js();">Click</button>

I have a form, which need variable number of input types.

<form action="" method="">
   [...]
   <div id="mezok">
      <div id="input_id">
         <input type="text" name="name" />
      </div>
   </div>
[...]
</form>

I add and remove further inputs (along with their divs!) via an ajax call. Javascript calls a php which generates a new input_id div, and then concatenates to the rest of the div id="mezok". Adding and removing inputs are fine as long as everything is empty. However, when I add a new div when there is something in the input, it clears the rest of the inputs.

document.getElementById("mezok").innerHTML = document.getElementById("mezok").innerHTML+http.responseText;

document.getElementById("mezok").innerHTML += http.responseText;

document.getElementById("mezok").innerHTML.concat(http.responseText);

(The last one is not working at all...)

TL;DR: concat input to input, values of inputs disappear. :'(


Solution

  • The code below could be a solution for you. In this way you're not going to overwrite the existing inputs with the associated values while you're adding new inputs.

    function js() {
        var inputElementToAppend = document.createElement('input');
        inputElementToAppend.innerHTML = "<input type=\"text\" name=\"name\" />";
        document.getElementById("example").appendChild(inputElementToAppend.firstChild);
    }
    <div id="example">
      <input type="text" name="name[]" />
    </div>
    <button type="button" onclick="js();">Click</button>

    Let me know if this worked for you.