How to store an input value in a variable and show it

Asked

Viewed 2,705 times

3

I’m trying to get a value from some inputs with Javascript to show them in a specific order.

<form id="formulario" name="" method="" action="">

        <p><h2 id="titulo-form">Dados do Livro</h2></p>
        <p><label for="nome">Nome do Autor:</label>
            <input type="text" name="nome" id="nome"maxlength="80"/></p>

        <p><label for="sobre">Sobrenome do Autor:</label>
            <input type="text" name="sobre" id="sobre"maxlength="80"/></p>

        <p><label for="titulo">Título:</label>
            <input type="text" name="titulo" id="titulo"maxlength="80"/></p>

In this case, I would like to show the order: Author’s surname > Author’s name > Title

I don’t have much experience with JS, so the basic thing I tried was to store the inputs the variables in this way, and link the generate function to the form’s Ubmit, however, I don’t know how to return it

function gerar() {
  var nomeAutor = document.getElementsById('nome'); 
  var sobreNome = document.GetElementById('sobre');
  var titulo = document.getElementsById('titulo');
}
  • Do you want to show whenever they change? or when the page clicks? or when the form is submitted?

  • When the form is submitted

  • Donizete, post attempt JS

2 answers

5


You can fetch the value of each input with

form.querySelector(`[name="${name}"]`).value

and then to create a string with these values you can do for example

form.querySelector(`[name="${name}"]`).value

Example:

const form = document.getElementById('formulario');
form.addEventListener('submit', function(e) {
  e.preventDefault();
  const [sobre, nome, titulo] = ['sobre', 'nome', 'titulo'].map(
    name => form.querySelector(`[name="${name}"]`).value
  );
  alert(`${sobre}, ${nome} - ${titulo}`);
});
<form id="formulario" name="" method="" action="">

  <p>
    <h2 id="titulo-form">Dados do Livro</h2>
  </p>
  <p><label for="nome">Nome do Autor:</label>
    <input type="text" name="nome" id="nome" maxlength="80" /></p>

  <p><label for="sobre">Sobrenome do Autor:</label>
    <input type="text" name="sobre" id="sobre" maxlength="80" /></p>

  <p><label for="titulo">Título:</label>
    <input type="text" name="titulo" id="titulo" maxlength="80" /></p>
  <button type="submit">Enviar</button>
</form>

0

You can use a simple Javascript Alert on the screen by printing your variables:

Alert('  Sobrenome do autor > Nome do Autor > Título'+ sobreNome + nomeAutor + titulo);

Browser other questions tagged

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