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 :)
Related
I'm attempting to press the numpad 6 and that triggers pressing the comma key.
I've attempted but doesn't work.
<input name="text" value="" />
<script type="javascript/text">
$(function() {
$("input").keypress(function (e) {
if (e.which == 102) { //numpad 6
e = jQuery.Event("keydown"); // define this once in global scope
e.which = 188; // Comma
$(this).trigger(e);
}
});
});
</script>
How do i solve? The outcome i want is pressing the numpad 6, instead of a 6 appearing in the input a comma appears.
Maybe you want to do smt like this
$(function() {
$("input").keypress(function (e) {
if (e.which == 102) {
e.preventDefault();
$(this).val(e.currentTarget.value + ',')
}
});
});
I am trying to figure out when a key press is an empty space, so I did the following:
if (e.which == ' '){
}
however this does not work. Any idea why?
event.which returns the code of the character pressed. space key code is 32, so use it instead:
if (e.which === 32) {
//
}
Another way is to convert character to char code with .charCodeAt():
if (e.which === " ".charCodeAt(0)) {
//
}
CHECK: http://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes
Write a test code and alert what the keyCode is.
document.onkeypress = function(e) {
e = e || window.event;
console.log(e.keyCode || e.which);
};
Learn to debug and you would not be asking these simple questions.
jQuery would have been
$(document).keypress(
function (e) {
console.log(e.which);
}
);
Probably this is what you're looking for: (Assuming you use the keydown event.)
if(e.keyCode == '32') {
// Your code
}
jsFiddle:
http://jsfiddle.net/DeHFL/
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
I'm trying to do a function if enter is pressed while on specific input.
What I'm I doing wrong?
$(document).keyup(function (e) {
if ($(".input1").is(":focus") && (e.keyCode == 13)) {
// Do something
}
});
Is there a better way of doing this which would say, if enter pressed on .input1 do function?
$(".input1").on('keyup', function (e) {
if (e.key === 'Enter' || e.keyCode === 13) {
// Do something
}
});
// e.key is the modern way of detecting keys
// e.keyCode is deprecated (left here for for legacy browsers support)
// keyup is not compatible with Jquery select(), Keydown is.
event.key === "Enter"
More recent and much cleaner: use event.key. No more arbitrary number codes!
NOTE: The old properties (.keyCode and .which) are Deprecated.
const node = document.getElementsByClassName("input1")[0];
node.addEventListener("keyup", function(event) {
if (event.key === "Enter") {
// Do work
}
});
Modern style, with lambda and destructuring
node.addEventListener("keyup", ({key}) => {
if (key === "Enter") {
// Do work
}
})
If you must use jQuery:
$(document).keyup(function(event) {
if ($(".input1").is(":focus") && event.key == "Enter") {
// Do work
}
});
Mozilla Docs
Supported Browsers
$(document).keyup(function (e) {
if ($(".input1:focus") && (e.keyCode === 13)) {
alert('ya!')
}
});
Or just bind to the input itself
$('.input1').keyup(function (e) {
if (e.keyCode === 13) {
alert('ya!')
}
});
To figure out which keyCode you need, use the website http://keycode.info
Try this to detect the Enter key pressed in a textbox.
$(function(){
$(".input1").keyup(function (e) {
if (e.which == 13) {
// Enter key pressed
}
});
});
The best way I found is using keydown ( the keyup doesn't work well for me).
Note: I also disabled the form submit because usually when you like to do some actions when pressing Enter Key the only think you do not like is to submit the form :)
$('input').keydown( function( event ) {
if ( event.which === 13 ) {
// Do something
// Disable sending the related form
event.preventDefault();
return false;
}
});
It may be too late to answer this question. But the following code simply prevents the enter key. Just copy and paste should work.
<script type="text/javascript">
function stopRKey(evt) {
var evt = (evt) ? evt : ((event) ? event : null);
var node = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null);
if ((evt.keyCode == 13) && (node.type=="text")) {return false;}
}
document.onkeypress = stopRKey;
</script>
The solution that work for me is the following
$("#element").addEventListener("keyup", function(event) {
if (event.key === "Enter") {
// do something
}
});
Try this to detect the Enter key pressed in a textbox.
$(document).on("keypress", "input", function(e){
if(e.which == 13){
alert("Enter key pressed");
}
});
DEMO
A solution that worked for me is this:
<input onkeydown="if (event.key == 'Enter'){//do logic}else{}">
$(document).ready(function () {
$(".input1").keyup(function (e) {
if (e.keyCode == 13) {
// Do something
}
});
});
This code handled every input for me in the whole site. It checks for the ENTER KEY inside an INPUT field and doesn't stop on TEXTAREA or other places.
$(document).on("keydown", "input", function(e){
if(e.which == 13){
event.preventDefault();
return false;
}
});
Here is what I did for my angular project:
HTML:
<input
class="form-control"
[(ngModel)]="searchFirstName"
(keyup)="keyUpEnter($event)"
/>
TypeScript:
keyUpEnter(event: KeyboardEvent) {
if (event.key == 'Enter') {
console.log(event);
}
}
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()
}
});
});