event.keyCode return `undefined` - javascript

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.

Related

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 :)

A default button to an entire webpage to respond to the ENTER key press

Is it possible to set a default button for the ENTER key press for an entire webpage?
I googled and I came across the below code. But I'm not sure of what this line means var keycode = (event.keyCode ? event.keyCode : (event.which ? event.which : event.charCode)); So I thought of posting this question here at stackoverflow.
Thanks.
<script language="javascript">
$(document).ready(function () {
$("input").bind("keydown", function (event) {
var keycode = (event.keyCode ? event.keyCode : (event.which ? event.which : event.charCode));
if (keycode == 13) {
document.getElementById('btn').click();
return false;
} else {
return true;
}
});
});
</script>
Different browsers/devices1 support different properties of obtaining key codes. The ternary expression is the same as:
var keyCode;
if(event.keyCode) // if keyCode is supported get that #top-priority
keyCode = event.keyCode;
else if(event.which) // else, if .which is supported, get that
keyCode = event.which;
else // alas! nothing above is supported
keyCode = event.charCode; // we should take charCode
1 Devices for example EAN barcode reader has a charCode of 13 Since its .keyCode is 0 (falsy), the 1st if condition is failed. Courtesy - MLeFevre
With JQuery (if an option) I would do
$(document).keyup(function(evt) {
if (evt.keyCode == 13) {
// do your thing
}
}
This worked for me in Chrome,FF, Safari and Opera.
Also consider using various checks as in #Gaurang Tandon's answer to cover all hardware specs.

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

How do i call a js function on pressing enter key

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

Cancel the keydown in HTML

How can I cancel the keydown of a specific key on the keyboard, for example(space, enter and arrows) in an HTML page.
If you're only interested in the example keys you mentioned, the keydown event will do, except for older, pre-Blink versions of Opera (up to and including version 12, at least) where you'll need to cancel the keypress event. It's much easier to reliably identify non-printable keys in the keydown event than the keypress event, so the following uses a variable to set in the keydown handler to tell the keypress handler whether or not to suppress the default behaviour.
Example code using addEventListener and ignoring ancient version of Opera
document.addEventListener("keydown", function(evt) {
// These days, you might want to use evt.key instead of keyCode
if (/^(13|32|37|38|39|40)$/.test("" + evt.keyCode)) {
evt.preventDefault();
}
}, false);
Original example code from 2010
var cancelKeypress = false;
document.onkeydown = function(evt) {
evt = evt || window.event;
cancelKeypress = /^(13|32|37|38|39|40)$/.test("" + evt.keyCode);
if (cancelKeypress) {
return false;
}
};
/* For pre-Blink Opera */
document.onkeypress = function(evt) {
if (cancelKeypress) {
return false;
}
};
Catch the keydown event and return false. It should be in the lines of:
<script>
document.onkeydown = function(e){
var n = (window.Event) ? e.which : e.keyCode;
if(n==38 || n==40) return false;
}
</script>
(seen here)
The keycodes are defined here
edit: update my answer to work in IE
This is certainly very old thread.
In order to do the magic with IE10 and FireFox 29.0.1 you definitely must do this inside of keypress (not keydown) event listener function:
if (e.preventDefault) e.preventDefault();
jQuery has a nice KeyPress function which allows you to detect a key press, then it should be just a case of detecting the keyvalue and performing an if for the ones you want to ignore.
edit:
for example:
$('#target').keypress(function(event) {
if (event.keyCode == '13') {
return false; // or event.preventDefault();
}
});
Just return false. Beware that on Opera this doesn't work. You might want to use onkeyup instead and check the last entered character and deal with it.
Or better of use JQuery KeyPress
I only develop for IE because my works requires it, so there is my code for numeric field, not a beauty but works just fine
$(document).ready(function () {
$("input[class='numeric-field']").keydown(function (e) {
if (e.shiftKey == 1) {
return false
}
var code = e.which;
var key;
key = String.fromCharCode(code);
//Keyboard numbers
if (code >= 48 && code <= 57) {
return key;
} //Keypad numbers
else if (code >= 96 && code <= 105) {
return key
} //Negative sign
else if (code == 189 || code == 109) {
var inputID = this.id;
var position = document.getElementById(inputID).selectionStart
if (position == 0) {
return key
}
else {
e.preventDefault()
}
}// Decimal point
else if (code == 110 || code == 190) {
var inputID = this.id;
var position = document.getElementById(inputID).selectionStart
if (position == 0) {
e.preventDefault()
}
else {
return key;
}
}// 37 (Left Arrow), 39 (Right Arrow), 8 (Backspace) , 46 (Delete), 36 (Home), 35 (End)
else if (code == 37 || code == 39 || code == 8 || code == 46 || code == 35 || code == 36) {
return key
}
else {
e.preventDefault()
}
});
});

Categories