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

Asked

Viewed 986 times

0

I want to create a form with a button +, create more fields for the user to send as many forms as they want.

I tried this code, but to no avail:

   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>");
    }

1 answer

2


Here’s a simple example of how to add divs with 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, test on CODEPEN.

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

If you really want to forms separate, just change the ('div') for ('form'), and remove the form of html. But remember that in this case you may have problems with sending the data if the user changes more than one field.

The button needs the type="button" to prevent him from sending the form (the type standard is submit).

Browser other questions tagged

You are not signed in. Login or sign up in order to post.