Button to add new fields in a form, with pure JS

0

I want to create a form with a + button, which creates more fields so that the user can send as many forms as he wants.

I tried this code, but without success:

   var coluna = 1;
    function plus() {
        document.write('<button onclick="plus()">+</button><br><hr><br>');
        document.write("<form action='teste.php' name='form'>");
        coluna = coluna + 1;
        botao = coluna - 1;
        espacos = '<br><input type="text" name="assunto'+coluna+'"><br><br><textarea name="texto'+coluna+'" rows="3" cols="20"></textarea><br><br><button onclick="plus()">+</button><br><hr><br>';
        document.write("teste");
        document.write(coluna);
        document.write(espacos);
        document.write('<button onclick="document.form.submit()" id="submit'+coluna+'" name="rows" value="'+coluna+'">Enviar</button><br>');
        //document.write('<input type="submit" id="submit'+coluna+'" name="submit'+coluna+'" value="enviar">');
        document.getElementById('submit'+botao+'').style.visibility = "hidden";
        document.write("</form>");
    }
    
asked by anonymous 24.10.2016 / 04:03

1 answer

2

Here is a very simple example of how to add div s to fields in an existing form:

var line = 1;
function addInput(divName) {
  var newdiv = document.createElement('div');
  newdiv.innerHTML  = '['+line +']';
  newdiv.innerHTML += '<input type="text" name="text'+line +'_1" id="text'+line +'_1">';
  newdiv.innerHTML += '<input type="text" name="text'+line +'_2" id="text'+line +'_2">';
  document.getElementById(divName).appendChild(newdiv);
  line++;
}

addInput('lines');
<form id="myForm">
  <div id="lines"></div>
  <button type="button" onclick="addInput('lines')">+</button>
  <input type="submit" value="Enviar">
</form>

If you prefer, try CODEPEN .

Note that we are not using document.write , but rather creating elements directly with createElement .

If you really want% s of% s separated, just change form to ('div') , and remove ('form') from form . But remember that in this case you may have problems sending the data if you change more than one field.

The html needs button to prevent it from sending type="button" (the default form ).

    
24.10.2016 / 05:10