Generate HTML using Javascript

Asked

Viewed 96 times

1

I have a small form for phone registration, and I want the user to be able to click the "Add new phone" button and an identical copy of the form is created below, so the user can put as many phones as he wants.

inserir a descrição da imagem aqui

And this is HTML:

            <div id="divTelefone">
            Telefone:<br>
            <label for="frmDDD">DDD: </label>
            <input type="text" maxlength="2" size="3" id="frmDDD" name="frmDDD" placeholder="xx"></input>
            <label for="frmNumero">Número:</label>
            <input type="text" id="frmNumero" name="frmNumero" size="20" maxlength="9" placeholder="Somente números"></input><br><br>

            <label for="frmOperadora">Operadora Telefone:</label>
            <select id="frmOperadora" name="frmOperadora">
                <option value="0">-----</option>
                <option value="VV">Vivo</option>
                <option value="CL">Claro</option>
                <option value="TM">Tim</option>
                <option value="OI">Oi</option>
                <option value="NX">Nextel</option>
                <option value="AL">Algar</option>
                <option value="SE">Sercomtel</option>
                <option value="MV">MVNO's </option>
            </select>
            <label for="frmDescTel">Descrição do telefone:</label>
            <input type="text" id="frmDescTel" name="frmDescTel" maxlength="25" size="25" placeholder="ex: trabalho, pessoal..."></input>
        </div>
        <input type="button" name="frmAddTelefone" id="frmAddTelefone" value="Adicionar outro número" onclick="addTelefone()">
  • 1

    Where is the javascript you have already implemented to generate html?

  • You use jQuery?

  • I do not use Jquery

3 answers

2

Create a clone of the element with id Divtelefone:

Let clone = Document.querySelector('#divTelefone'). cloneNode( true );

Changes the id of the cloned html:

clone.setAttribute( 'id', newId );

Attach the newly created element to the p element (Note: Create a tag in the p type html)

Document.querySelector('p'). appendchild( clone );

Or else using jQuery:

$('#divTelefone'). clone(). attr('id', newId). appendTo('p');

  • But how could I change the id of each field within the div?

  • You would have to make the change one by one the same way you changed the div

2

First of all, you need to convert the form elements' numbers into an array, otherwise you won’t be able to get them in the backend when submitting the form.

You must put the clasps [] at the end of all Names, thus:

name="frmDDD[]"

Once this is done (in all fields), you can reproduce the contents of div#divTelefone, this way (see comments in the code):

var divtel = document.getElementById("divTelefone"); // seleciona a div
var clone = divtel.innerHTML; // copia o HTML da div, que será a fonte
function addTelefone(){
   
   var novotel = document.createElement("div"); // cria uma div
   novotel.className = "tels"; // atribui uma classe na nova div
   divtel.appendChild(novotel); // insere a nova div na div principal
   var last = document.querySelector(".tels:last-child"); // seleciona a última div criada
   last.innerHTML = clone; // insere o HTML copiando anteriormente na última div inserida
   var fors = last.querySelectorAll("[for]"); // seleciona todos os atributos "for"
   var ids = last.querySelectorAll("[id]"); // seleciona todos os atributos "id"
   var d = new Date(); // data de hoje
   var i = "_"+d.getHours()+d.getMinutes()+d.getSeconds()+d.getMilliseconds(); // número único para os "for" e "id"
   for(let x = 0; x < fors.length; x++){
      fors[x].setAttribute("for", fors[x].getAttribute("for")+i); // altera os for
      ids[x].id = ids[x].id+i; // altera os id
   }
}
<div id="divTelefone">
   Telefone:<br>
   <label for="frmDDD">DDD: </label>
   <input type="text" maxlength="2" size="3" id="frmDDD" name="frmDDD[]" placeholder="xx"></input>
   <label for="frmNumero">Número:</label>
   <input type="text" id="frmNumero" name="frmNumero[]" size="20" maxlength="9" placeholder="Somente números"></input><br><br>
   <label for="frmOperadora">Operadora Telefone:</label>
   <select id="frmOperadora" name="frmOperadora[]">
      <option value="0">-----</option>
      <option value="VV">Vivo</option>
      <option value="CL">Claro</option>
      <option value="TM">Tim</option>
      <option value="OI">Oi</option>
      <option value="NX">Nextel</option>
      <option value="AL">Algar</option>
      <option value="SE">Sercomtel</option>
      <option value="MV">MVNO's </option>
   </select>
   <label for="frmDescTel">Descrição do telefone:</label>
   <input type="text" id="frmDescTel" name="frmDescTel[]" maxlength="25" size="25" placeholder="ex: trabalho, pessoal..."></input>
</div>
<input type="button" name="frmAddTelefone" id="frmAddTelefone" value="Adicionar outro número" onclick="addTelefone()">

Remarks:

  • The attributes for and id are dynamically changed each time a new form is inserted.
  • Another thing is that there is no closing tag </input>. The tag <input>, HTML5 does not need to be closed.
  • 2

    It is noteworthy that the tag input should not be closed and all ids in an HTML page should be unique.

  • 1

    I solved the for+ids issue. ;)

1

When you want to add HTML to elements of a page you can manipulate the property Element.innerHTML.

In this example I started with a div divTelefone empty and each time the button to add phone is pressed it inserts the form components.

var telid = 1;

function addTelefone(){
 
   document.getElementById("divTelefone").innerHTML += `

    <div id="Telefone` + telid + `">
        Telefone:<br>
        <label for="frmDDD">DDD: </label>
        <input type="text" maxlength="2" size="3" id="frmDDD" name="frmDDD" placeholder="xx"></input>
        <label for="frmNumero">Número:</label>
        <input type="text" id="frmNumero" name="frmNumero" size="20" maxlength="9" placeholder="Somente números"></input><br><br>

        <label for="frmOperadora">Operadora Telefone:</label>
        <select id="frmOperadora" name="frmOperadora">
            <option value="0">-----</option>
            <option value="VV">Vivo</option>
            <option value="CL">Claro</option>
            <option value="TM">Tim</option>
            <option value="OI">Oi</option>
            <option value="NX">Nextel</option>
            <option value="AL">Algar</option>
            <option value="SE">Sercomtel</option>
            <option value="MV">MVNO's </option>
        </select>
        <label for="frmDescTel">Descrição do telefone:</label>
        <input type="text" id="frmDescTel" name="frmDescTel" maxlength="25" size="25" placeholder="ex: trabalho, pessoal..."></input>
    </div>

   `;
    telid++;
  
}
<html>
    <body>

        <div id="divTelefone">
            
        </div>
        <input type="button" name="frmAddTelefone" id="frmAddTelefone" value="Adicionar telefone" onclick="addTelefone()">

    </body>
</html>

Browser other questions tagged

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