Ajax Commit - Enter

Asked

Viewed 132 times

2

How can I make a commit 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: <input type="text" name="nome" id="nome" placeholder="Digite seu Nome">
<button>Enviar</button>

How can I do, so that when focusing on input when the enter key is pressed, it is submitted?

1 answer

2


You can do it like 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: <input type="text" name="nome" id="nome" placeholder="Digite seu Nome">
<button>Enviar</button>

The important thing is to find the code of the key that was pressed, 13 to Enter.

Explanation:

  • $('#nome').on('keyup', function(event) { - when the element with the ID nome receive input from a key (at the time of release of the key) it runs a function

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

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

  • Can you explain how the code works? At least this code: $('#name'). on('keyup', Function(Event) { if (Event.which !== 13) Return; var name = this.value;

  • @Carloshenrique yes, of course! 1 min

  • @Carloshenrique I just updated!

  • o . wich what does it mean? And what is it for?

  • 1

    @Carloshenrique event is an object that Javascript gives us. jQuery gives some more properties to this object, in this case the which is a native property but jQuery normalizes. That is, in some browsers that do not have this which jQuery gives you a value in it, to always be the same in any browser. If you use native code the event.key is more correct. But in jQuery the .which is what you should wear.

Browser other questions tagged

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