66

I have a text field which is showing a value. What I want is when the user writes a new value in that text field and presses enter, an ajax function is triggered to do a pagination operation. I have a text field like this:

<input type="text" id="page" name="page" value="<?php echo($this->pn);?> />

And when a user writes any new value and presses enter, I want the following ajax function triggered:

update_ajax2({rpp:<?php echo($this->rpp);?>,pn:document.page.paged.value,filter:'<?php echo($this->filter);?>',orderby:'<?php echo($this->orderby);?>'});

I tried using the keypress event to detect if(e.which===13) but this doesn't solve the problem. Can anyone guide me?

2
  • Why doesn't acting on the keypress event solve the problem? Do you get an error? Have you tried keyup instead? Apr 12, 2011 at 7:13
  • @ctcherry it calls the function 2 types on 1 key press. First it loads the value that I want and then on same key press it loads function fo the value attribute of textbox Apr 12, 2011 at 7:19

4 Answers 4

150
<input type="text" id="txt">

$('#txt').keydown(function (e) {
    if (e.keyCode == 13) {
        alert('you pressed enter ^_^');
    }
})

On jsfiddle.

Update (June 2022)

Note that keyCode has been deprecated. Use KeyboardEvent.code or KeyboardEvent.key properties instead:

if (e.key === "Enter") {
   // Pressed enter
}
5
  • @experimentX thanks dude but it is always having the value that is in value attribute of textbox. It doesn't detects new value.... Apr 12, 2011 at 7:18
  • @AwaisQarni could you post a fiddle??
    – S L
    Apr 12, 2011 at 7:19
  • @AwaisQarni i mean on jsfiddle.net or update mine jsfiddle.net/VCdEn
    – S L
    Apr 12, 2011 at 7:22
  • @AwaisQarni ... nope.. its not due to value. it's due to the form element. i.e. form is being submitted(as default). to prevent it. e.preventDefault() update here jsfiddle.net/FxU9X/6
    – S L
    Apr 12, 2011 at 7:35
  • Standard usability says to use key-up event instead of key-down. It gives them the option to cancel after key down by pressing a modifier (like esc) before lifting up. Also it is how most libraries will catch the event so it brings consistency. Keydown is for data entry and key up is for events. Jan 4, 2016 at 18:02
4

Use this, it works for me :)

$("#search-txt" ).on( "keydown", function(event) {
    if(event.which == 13) 
        return false;//do something
});
1

Check out this plugin: https://github.com/jeresig/jquery.hotkeys

0

Key pressed event should work try it

function keyPressedTest(a)
{
    a=(a)?a:window.event;
    input=(a.target)?a.target:a.srcElement;
    if(a.keyCode==13)
    {
        your_function()
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.