9

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 ?

1
  • 2
    Inline event handlers are the wrong approach. Keep JS in .js files.
    – zzzzBov
    Sep 28, 2012 at 15:10

3 Answers 3

25

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

1
  • 1
    Simple and worked, thank you =) (I need to wait more 5 minutes do check as "accepted" your answer Sep 28, 2012 at 15:12
4

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
    }
}
2
  • 2
    Inline JS event handlers are almost always a bad idea.
    – zzzzBov
    Sep 28, 2012 at 15:09
  • 3
    I'm not refactoring the OP's code just answering his question. No need for a downvote. Sep 28, 2012 at 15:09
4

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');
    }
}​

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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