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

3

I know how to do it with PhP but to catch a little bit with javascript, I wanted to use the "name" and "email" fields to put what the user types inside a variable name and another email within JavaScript. >     

asked by anonymous 03.06.2017 / 05:21

4 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

Make sure you use getElementsByName or querySelectorAll , or getElementsByClassName isso vi dar uma coleção e não podes usar .value diretamente, 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" />
    
03.06.2017 / 09:52
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");
    
03.06.2017 / 21:50
0
var input = document.getElementsByName('input').value;

or using id:

var input = document.getElementsById('id').value;

If you prefer to use jquery:

var input = $("input[name="name"]").val();

with id:

var input = $("#id").val();
    
03.06.2017 / 06:02
0

Good evening, it's simple:

var nome = document.getElementByName('nome_do_input').value;
    
03.06.2017 / 05:28