How can I capture the names of an html form and put in a variable in Javascript

Asked

Viewed 156 times

3

I know how to do with Php but to catch a little bit with javascript, I wanted to use the fields "name" and "email" to put what the user type inside a variable name and another email inside Javascript.

3 answers

1


You can use:

  • .querySelector('input[name="nome"]').value
  • .getElementsByName('nome')[0].value
  • or use id (#) or class (.) and selectors:
    • document.getElementById('id').value
    • document.getElementByClassName('classe')[0].value
    • document.querySelectorAll('.classe')[0].value

Notice if you use getElementsByName or querySelectorAll, or getElementsByClassNameisso vi dar uma coleção e não podes usar.valuediretamente, tens de usar[0]` if you want the first element of the collection, etc...

Example:

var nome = document.querySelector('input[name="nome"]');
var email = document.querySelector('input[name="email"]');

nome.value = 'Bianca San';
email.value = '[email protected]';
input {
  padding: 5px;
  display: block;
  width: 200px;
}
<input name="nome" />
<input name="email" />

1

Well, if you want to capture the name attribute of the input tag, it would look like this :

 var campo = document.querySelector("input:nth-child(1)");
 var nameCampo = campo.getAttribute("name");

0

Good night, it’s simple:

var nome = document.getElementByName('nome_do_input').value;
  • thank you so much :)

  • 1

    Missed the "s"...

  • document.getElementsByName gives a collection for this document.getElementsByName('nome_do_input').value won’t work.

Browser other questions tagged

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