How do i call a js function on pressing enter key - javascript

I'd like to know how I can initiate a javacsript function when pressing the enter key. I'm trying to create a function called handleEnter(event, fn).
I want to use the function on an input field eg:
onkeypress="return handleEnter(event, update_field(this));

For your function called onkeypress, check the event's .keyCode or .which value, and see if it is equal to 13.
function handleEnter(e, func){
if (e.keyCode == 13 || e.which == 13)
//Enter was pressed, handle it here
}
IIRC, IE uses event.which, and Firefox will use e.keyCode to see which key was pressed.

I think I've solved it.
On the input field I've got:
<input onkeypress="return handleEnter(event, update_field, this, 'task');" type="text" />
For my function I've got:
function handleEnter(e, callback, obj, field){
if(e){
e = e
} else {
e = window.event
}
if(e.which){
var keycode = e.which
} else {
var keycode = e.keyCode
}
if(keycode == 13) {
var tstid = $(obj).parent().find('input[type=hidden]').val();
callback.apply(this, [field, $(obj).val(), tstid ]);
}
}
and it seems to be working fine now.

You can try this shorthand
<input type=”text” onKeydown=”Javascript: if (event.keyCode==13) Search();”>
<input type=”button” value=”Search” onClick=”Search();”>
From http://www.techtamasha.com/call-javascript-function-on-pressing-enter-key/25

Related

event.keyCode return `undefined`

I am trying to run a simple JavaScript function and it does not return the correct value. I want to capture the Enter key code and it doesn't work as expected.
The code event.keyCode returns undefined. In both Chrome and IE 9
My JS:
var viewModel = {
addOnEnter: function (event) {
alert(event.keyCode); returns undefined
var keyCode = (event.which ? event.which : event.keyCode);
if (keyCode == 13)
{
//.. my code
}
return true;
}
}
Binding it like this:
<input type="text" data-bind="event: { keypress: addOnEnter }" />
Both event.keyCode and event.which returns undefined.
The event is the second argument to the handler.

Detect Comma/Enter key press

There are some comma separated values in an input field. I want to alert a message when I am pressing the COMMA(,) or ENTER key. I have given the code that I used for this, but didn't work. Is there anything inefficient about this?
$(document).on("keyup", '.tagsinput', function (e) {
if (e.which == 13 || e.which == 44) {
alert('comma added');
}
});
The keycode (which in jQuery) for a comma is 188
There is a brilliant tool for this here
$(document).on("keyup", '.tagsinput', function (e) {
if (e.keyCode == 188) { // KeyCode For comma is 188
alert('comma added');
}
});
Demo: http://jsfiddle.net/tusharj/3yLwgwhb/
Try using keypress instead of keyup:
$(function() { //<-- you are missing this
$(document).on("keypress", '.tagsinput', function(e) { //<-- note, its keypress
console.log('key pressed ', e.which);
if (e.which == 13 || e.which == 44) {
return false; //<-- prevent
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type='text' class='tagsinput' />
<input type='text' class='tagsinput' />
Use event.key and modern JS!
No number codes anymore. You can check for Enter or , key directly.
const input = document.getElementById("inputId");
input.addEventListener("keypress", function (event) {
if (event.key === "Enter" || event.key === ",") {
// Do something
}
});
Mozilla Docs
Supported Browsers
You shouldn't listen for keyup, better way is to listen for keypress:
$('.tagsinput').keypress(function (e) {
if (e.which == 13 || e.which == 44) {
alert('comma added');
}
});
Jsfiddle here: http://jsfiddle.net/doe7qk6r/
$(document).ready(function(){
$("#tagsinput").bind('keypress', function(e) {
var code = e.keyCode || e.which;
if(code == 44) { // comma key code is 44
str= $('#tagsinput').val();
str.substring(0, str.length - 2);
arr = str.split(",");
key = arr[arr.length-1];
arr.splice(arr.length-1, 1);
if(arr.indexOf( key )!=-1){
alert("Duplicate detected : "+key);
//uncomment the next line to remove the duplicated word just after it detects !
//$('#tagsinput').val(arr);
}
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<label>Sub Location Names</label>
<input name="tagsinput" id="tagsinput" class="tagsinput" data-maxwidth="200" id="ptag" value="" />
hope this will work for you :)

clicking a button with a keyboard

lets say I have a button like this:
<input id="a" type="button" value="A" />
and I want it so that if I press the "a" key on the keyboard, it visually acts as though I am clicking the button with the mouse.
Is there a way to do that?
document.onkeydown = function (evt) {
var keyCode = evt ? (evt.which ? evt.which : evt.keyCode) : event.keyCode;
if (keyCode == 65) {
document.getElementById("a").click();
// Your function here.
}
};
for other keycodes refer
Keycodes
Have a look at HTML5's globalaccesskey:
http://www.w3schools.com/tags/att_global_accesskey.asp
** EDIT **
Or if you are looking for a pure javascript way, you could try this:
document.onkeypress = textsizer;
function textsizer(e){
var evtobj=window.event? event : e;
var unicode=evtobj.charCode? evtobj.charCode : evtobj.keyCode;
var actualkey=String.fromCharCode(unicode);
if (actualkey=="e"){
document.getElementById('a').click();
}
}
This should work: (Assumes JQuery)
$(document).keyup(function (event) {
if (event.which == 65) { // "A" key
$('#a').click();
}
});

How to Detect Enter key in Firefox?

I am trying to detect Enter Key. Here is my code.
HTML
<input name="txtTest" type="text" id="txtTest" onkeyup="CheckKey()"/>
Javascript
function CheckKey()
{
var e = window.event;
var code = e.keyCode ? e.keyCode : e.which;
if(code === 13)
{
alert("You press Enter key.");
}
}
This code is working in other browsers but not in Firefox Why?
Here is jsFiddle
Please provide answers using javascript only.
I believe you have to pass the event object to the handler:
<input name="txtTest" type="text" id="txtTest" onkeyup="CheckKey(event)"/>
<!-- passes event object ^ -->
function CheckKey(e) //receives event object as parameter
{
var code = e.keyCode ? e.keyCode : e.which;
if(code === 13)
{
alert("You press Enter key.");
}
}
Fiddle
You should separate JavaScript code from HTML.
Try something like this - key should work on all browsers:
<input type="text" id="txtTest" onkeyup="CheckKey(e)"/>
function CheckKey(e) {
var key = e.charCode ? e.charCode : e.keyCode ? e.keyCode : 0;
if(key === 13)
{
alert("You press Enter key.");
}
}
Or as suggested with jQuery (separated JavaScript code from HTML) - use event.which:
<!--HTML file e.g. index.html-->
<input type="text" id="txtTest" />
//JavaScript file e.g. script.js - you have to include that script in your HTML file
$(function(){
$('#txtTest').on('keyup', function(e){
if(e.which === 13)
{
alert("You press Enter key.");
}
});
});
Use event.key instead of event.keyCode!
function CheckKey(event) {
if (event.key === "Enter") {
// Do something
}
};
Mozilla Docs
Supported Browsers

Problem with KeyPress Javascript function

I call a javascript function from a textbox by using OnKeyPress="clickSearchButton()"
Here is my function:
function clickSearchButton()
{
var code = e.keyCode || e.which;
var btnSearch = document.getElementById("TopSubBanner1_SearchSite1_btnSearchSite");
if(code == 13);
{
btnSearch.click();
return false;
}
}
My problem is that this function fires when the user hits the enter button in any textbox, not just the one that calls the function. What am I missing?
EDIT: Still not working correctly. So I'll throw my HTML out there if that helps.
<input name="TopSubBanner1:SearchSite1:txtSearch" type="text" id="TopSubBanner1_SearchSite1_txtSearch" OnKeyPress="clickSearchButton(this)" /><input type="submit" name="TopSubBanner1:SearchSite1:btnSearchSite" value="Search" id="TopSubBanner1_SearchSite1_btnSearchSite" />
Also, this is an ASP.NET page if that makes a difference.
The event is by default passed as an argument to your function, but your not capturing it as a parameter. If you capture it, the above should work correctly.
function clickSearchButton(e)
{
e = e || window.event //for IE compliane (thanks J-P)
//etc
or
function clickSearchButton()
{
var e = arguments[0];
e = e || window.event;
Also you have an extra semicolon as Kevin pointed out.
function clickSearchButton(e)
{
var code;
if(window.event)
code = e.keyCode;
else
code = e.which;
var btnSearch = document.getElementById("TopSubBanner1_SearchSite1_btnSearchSite");
if(code == 13)
{
btnSearch.click();
return false;
}
}
and your calling method should be:
onkeypress="clickSearchButton(event)"

Categories