Submission Ajax - Enter

2

How can I make a submission with ajax using the enter key? That is, I have the following code:

 var nome = $("#nome").val();
 jQuery.ajax({
	            method: "get",
	            url: "teste.php",
	            data: { "nome": nome },
	            success: function(data){
	                alert("Enviado com Sucesso!");
	            }
        	});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>Nome:<inputtype="text" name="nome" id="nome" placeholder="Digite seu Nome">
<button>Enviar</button>

How can I do this, so that when I press the enter key, I will be submitted to the input?

    
asked by anonymous 17.09.2017 / 14:04

1 answer

2

You can do this:

$('#nome').on('keyup', function(event) {
  if (event.which !== 13) return;
  var nome = this.value;
  jQuery.ajax({
    method: "get",
    url: "teste.php",
    data: {
      "nome": nome
    },
    success: function(data) {
      alert("Enviado com Sucesso!");
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>Nome:<inputtype="text" name="nome" id="nome" placeholder="Digite seu Nome">
<button>Enviar</button>

The important thing is to look for the key code that was pressed, 13 for Enter.

Explanation:

  • $('#nome').on('keyup', function(event) { - when the element with the ID nome receives the input of a key (at the moment of releasing the key) it runs a function

The function called by .on('keyup' automatically receives the argument event that contains information about the keyboard event, in this case the number of the key pressed. If event.which is 13 this is the code for the enter key and we know that this key was pressed.

This function has as this the element that received the event. This is why this.value gives us the current value of the element.

    
17.09.2017 / 14:07