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 ?
To trigger a click button on ENTER key, We can use any of the keyup(), keydown() and keypress() events of jQuery. keyup(): This event occurs when a keyboard key is released. The method either triggers the keyup event, or to run a function when a keyup event occurs.
addEventListener("keydown", function (e) { if (e. code === "Enter") { //checks whether the pressed key is "Enter" validate(e); } }); function validate(e) { var text = e. target. value; //validation of the input... }
Method 1: Use addEventListener() Method Get the reference to the button. For example, using getElementById() method. Call addEventListener() function on the button with the “click” action and function passed as arguments.
In plain JavaScript, you can use the EventTarget. addEventListener() method to listen for keyup event. When it occurs, check the keyCode 's value to see if an Enter key is pressed.
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
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');
}
}
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
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With