Turning a value of a variable into a paragraph

2

I want to know how I can, instead of sending the result of the pro alert function, create a paragraph, for example. Remembering that this doubt is to help me with future projects, so I am putting a very simple code.

Code:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" lang="pt-br">
    <title>Formulário teste</title>
    <script type="text/javascript">
        function enviar(){
            var formulario = document.getElementById('formulario');

            var nome2 = formulario.nome.value;
            alert(nome2);

        }
    </script>
</head>
<body>
    <h1>Dados para cadastro</h1>

    <form id="formulario">
        <label for="nome">Nome:</label>
        <input id="nom" type="nome" name="nome">

        <label for="cpf">CPF:</label>
        <input type="cpf" name="cpf">

        <label for="cep">CEP</label>
        <input type="cep" name="cep">

        <button onclick="enviar()">Submit</button>
    </form>

    <h1 id="receber"></h1>

</body>
</html>
    
asked by anonymous 07.02.2018 / 01:02

2 answers

0

In this example, the h1 tag will receive the contents of the variable only when the send function is triggered. If you wish to do this, just remove the code from the function and put it in another one, there will be several options to call the function even automatically when the page loads. Example 2. Home Example 1

<h1 id="receber"></h1>  

<script>
    function enviar(){
        var formulario = document.getElementById('formulario');

        var nome2 = formulario.nome.value;
        //alert(nome2);
       document.getElementById( 'receber' ).innerHTML = nome2;
    }
</script>

Example 2

<script>
  $( document ).ready( function () {
    document.getElementById( 'receber' ).innerHTML = nome2;
  } );
</script>
    
07.02.2018 / 01:26
2

You can use document.createElement . But add the type="button" attribute to the submit button so that the page is not reloaded. See commented example:

function enviar(){
   var formulario = document.getElementById('formulario');
  
   var nome2 = formulario.nome.value;
   var paragrafo = document.createElement("p"); // crio o elemento <p>
   var texto = document.createTextNode(nome2); // defino o texto
   paragrafo.appendChild(texto); // insiro o texto no elemento <p>
   document.body.appendChild(paragrafo); // insiro na página
}
<h1>Dados para cadastro</h1>

 <form id="formulario">
     <label for="nome">Nome:</label>
     <input id="nom" type="nome" name="nome">

     <label for="cpf">CPF:</label>
     <input type="cpf" name="cpf">

     <label for="cep">CEP</label>
     <input type="cep" name="cep">

     <button onclick="enviar()" type="button">Submit</button>
 </form>

 <h1 id="receber"></h1>
    
07.02.2018 / 01:14