Detect enter key with jquery

1

Good afternoon I have the following doubt, as you will see I need that when the enter key is pressed I execute a function that I already have created.

If it detects the key and enters the function that I have created because it shows the alerts that I put inside it, but the problem is that the ajax code that I have inside that function is not executed because this is happening?

This is the code I'm using

$(document).ready(function(){     
      $("#dato").keypress(function(e) {
        if(e.which == 13) {
          obtenerDatos();
        }
      });
});

function obtenerDatos()
{
    var valor = $("#dato").val();

    $.ajax({
      type: 'POST', 
      url:  'getDatos.php',
      data: "valor=" + valor,
      success: function(response){
            $("#wrap").html(response);
      }
    });
}
    
asked by derloopkat 07.11.2017 в 22:16
source

2 answers

3

I recommend the following modification:

$(document).ready(function(){
    $("#dato").keypress(function(e) {
        //no recuerdo la fuente pero lo recomiendan para
        //mayor compatibilidad entre navegadores.
        var code = (e.keyCode ? e.keyCode : e.which);
        if(code==13){
            obtenerDatos();
        }
    });
});

function obtenerDatos() { var valor = $("#dato").val();
    $.ajax({
      type: 'POST', 
      url:  'getDatos.php',
      data: "valor=" + valor,
      success: function(response){
            $("#wrap").html(response);
      }
    });
}
    
answered by 07.11.2017 / 22:26
source
0

I found a solution and it's the one that worked for me, you'll see when you press enter it happened that the page was reloaded, what I needed is that the page was not reloaded when I pressed the enter, so I found out that I had to cancel the enter in the text type input

And modify my code like this:

$ ("# data"). keypress (function (e) {         var code = (e.keyCode? e.keyCode: e.which);         if (code == 13) {           get information();           return false;         }       });

    
answered by 07.11.2017 в 22:54