Fred Vicentin
Fred Vicentin

Reputation: 977

Call a function when the enter button is pressed via Javascript

I have a problem, I want to call a function inside a textbox, when I press enter, this is my code

<input  type="text" value="DIGITE O LOCAL" onclick="this.select()" size="20" id="endereco">

I want to put something like onenterpress="doSomething()"

How can I do this ?

Upvotes: 9

Views: 42558

Answers (3)

2stripe
2stripe

Reputation: 61

Daniel Li's answer is the slickest solution, but you may encounter a problem with IE and event.keyCode returning undefined, as I have in the past. To get around this check for window.event

document.getElementById('endereco').onkeydown = function(event){
    var e = event || window.event;
    if(e.keyCode == 13){
        alert('5');
    }
}​

Upvotes: 4

Daniel Li
Daniel Li

Reputation: 15379

If you want to use obtrusive Javascript:

<input type="text" value="DIGITE O LOCAL" onclick="this.select()" 
onKeyDown="if(event.keyCode==13) alert(5);" size="20" id="endereco">

Handling this unobtrusively:

document.getElementById('endereco').onkeydown = function(event) {
    if (event.keyCode == 13) {
        alert('5');
    }
}

Your best choice is to use the latter approach. It will aid in maintainability in the long run.

Reference: http://en.wikipedia.org/wiki/Unobtrusive_JavaScript

Upvotes: 25

SeanCannon
SeanCannon

Reputation: 77966

HTML

<input  type="text" value="DIGITE O LOCAL" onkeypress="doSomething(this, event)" onclick="this.select()" size="20" id="endereco">

JS

function doSomething(element, e) {
    var charCode;

    if(e && e.which){
        charCode = e.which;
    }else if(window.event){
        e = window.event;
        charCode = e.keyCode;
    }

    if(charCode == 13) {
        // Do your thing here with element
    }
}

Upvotes: 4

Related Questions