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
Solution 1:
If you want to use obtrusive Javascript:
<inputtype="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
Solution 2:
HTML
<inputtype="text" value="DIGITE O LOCAL" onkeypress="doSomething(this, event)" onclick="this.select()" size="20"id="endereco">
JS
functiondoSomething(element, e) {
var charCode;
if(e && e.which){
charCode = e.which;
}elseif(window.event){
e = window.event;
charCode = e.keyCode;
}
if(charCode == 13) {
// Do your thing here with element
}
}
Solution 3:
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');
}
}
Post a Comment for "Call A Function When The Enter Button Is Pressed Via Javascript"