onkeyup handler not being called - javascript

I found a post on SO that was actually posted yesterday (I cannot find it now) that says my code below should work, but it does not -- the 'handleRtnKey(e)' function below is never called - why?
<input type="text" id="zer" onkeyup="handleRtnKey(e)"/>
// my javascript function -- by the way, I will not be using jquery.
function handleRtnKey(e)
{
alert("Just entered handleRtnKey()");
if (!e)
{
e = window.event; // resolve event instance for IE
}
alert("Just entered handleRtnKey(), e.keyCode is: " + e.keyCode);
alert("Just entered handleRtnKey(), e is: " + e);
if (e.keyCode == '13')
{
alert("handleRtnKey: got the RTN key up event.");
return false;
}
}
None of the alerts fire.
I found a SO post from yesterday that had this near exact code (without my alerts) that claimed to work fine (sorry I cannot re-find that SO post).
I need to use straight javascript (not jquery) to get the key code of the keyup event in my input text box -- that's all I need to do, and if it is the Return key, then I'll take some action, but for now I cannot get the above code to fire that handleRtnKey() function -- why?
EDIT
Damon introduced me to the keyword 'event' and the above code now works fine -- I simply renamed the argument in the html code from 'e' to 'event' and the javascript handler now works fine -- here is the only modification to the code above I had to make:
// OLD
<input type="text" id="zer" onkeyup="handleRtnKey(e)"/>
// NEW
<input type="text" id="zer" onkeyup="handleRtnKey(event)"/>
NOTE: the javascript function handleRtnKey(e) is unchanged, there was no reason for my to change that function's signature, it looks like below and works fine now:
function handleRtnKey(e)
{
alert("Just entered handleRtnKey()");
if (!e)
{
e = window.event; // resolve event instance for IE
}
alert("Just entered handleRtnKey(), e.keyCode is: " + e.keyCode);
alert("Just entered handleRtnKey(), e is: " + e);
if (e.keyCode == '13')
{
alert("handleRtnKey: got the RTN key up event.");
return false;
}
}
THANKS DAMON.

you don't need argument at all, just use event:
function handleRtnKey() {
event = event || window.event; // for cross-browsing
alert(event); // or do whatever you want with it
};
DEMO

The problem is that you call the method with parameter which you don't have. e is not declared. If you remove it it will work. This code worked for me:
<input type="text" id="zer"/>
<script>
window.onload = function () {
document.getElementById("zer").onkeyup = function(event) {
if (event.keyCode == 13) {
alert("Just entered handleRtnKey()");
}
};
};
</script>

The solution to my problem was as Damon pointed out in his comments above -- I was not aware there was a predefined 'event' keyword and when I used 'event' instead of 'e' in my code above, it worked fine.

Related

Write keycode to console. Repeatedly

I'm having a small mental block: I've got a javascript function in html that writes the keycode when a key is pressed. I've got it hooked up to a function that tells me exactly what character and keycode is pressed (not included).
My question is how do I modify the code to print up keypress after keypress after keypress. At the moment it does just the one and then that's that.
There's a rather nicer version of what I'm doing here on css-tricks, with the code here
Admittedly the latter is running JS Babel which might be the difference. However, I need to do this in pure Javascript.
Bonus points: is keypress one word or two ;)
</script>
function check_keycode(e)
{
var keycode;
if (window.event)
{
keycode = window.event.keyCode;
}
else if (e)
{
keycode = e.which;
}
document.write("keycode: " + keycode);
//console.log("keycode: " + keycode);
}
</script>
I think you want some thing like this. I tried with chrome console.
HTML
<p id="log"></p>
JS:
const log = document.getElementById('log');
document.addEventListener('keypress', logKey);
function logKey(e) {
log.textContent += ` ${e.key}`;
}

Disable Backspace

I want to disable the Backspace button any time I click the browser page. I have written this piece of code (the second if is making sure that this would work for any version of IE - 11 or lower):
<PUBLIC:COMPONENT TAGNAME="menucontrol">
<PUBLIC:ATTACH EVENT="onclick" FOR="document" ONEVENT="RemoveBackspace();"/>
<SCRIPT language="javascript">
function RemoveBackspace() {
document.onkeydown = function (){
if(event.keyCode === 8) {
if(typeof event.preventDefault === 'function'){
event.preventDefault();
}
else{
event.returnValue = false;
}
}
};
}
</SCRIPT>
...
</PUBLIC:COMPONENT>
If I introduce an alert function in the RemoveBackspace() function, the message appears. I don't know what's wrong with this code. Should I use a different approach?
You forgot to pass the event to the function.
document.onkeydown = function (event){
if(event.keyCode === 8) {
event.preventDefault();
}
};
Look at the first line of my code. I also removed the unnecessary second if/else statement, as the code works fine without it. Don't worry, everyone makes mistakes like this at first. :P

JS onkeydown/onkeyup - convert to jQuery keydown/keyup

I currently have some js for phone number validation that is using inline event listeners in the input field. I need to change this example so that instead of attaching the event listeners inline, I would be targeting the DOM element in jQuery and adding the event listeners. Here's a working example of what I have so far: http://jsfiddle.net/yVdgL/21/
window.mask = function (e,f){
var len = f.value.length;
var key = whichKey(e);
if((key>=47 && key<=58) || (key>=96 && key<=105))
{
if( len==1 )f.value='('+f.value
else if(len==4 )f.value=f.value+')'
else if(len==8 )f.value=f.value+'-'
else f.value=f.value;
}
}
function whichKey(e) {
var code;
if (!e) var e = window.event;
if (e.keyCode) code = e.keyCode;
else if (e.which) code = e.which;
return code
}
and
<input type="text" name="phone" id="phone" onkeydown="mask(event,this)" onkeyup="mask(event,this)" maxlength="13" />
I tried this but was unable to achieve the functionality that I need.
i have update you jsfiddle example:-
jQuery(document).ready(function(){
jQuery('#edit-phone1').keyup(function(event){
mask(event,this);
});
jQuery('#edit-phone1').keydown(function(event){
mask(event,this);
});
});
click here to see working example:-
http://jsfiddle.net/yVdgL/38/
or you can try :-
$(document).ready(function() {
$('#edit-phone1').on("keyup keydown", function(e) {
mask(e, this);
});
});
link for this is:-http://jsfiddle.net/yVdgL/56/
In older, pre-HTML5 browsers, $("#phone").keyup( function ) or keydown is definitely what you're looking for.
In HTML5 there is a new event, "input", which behaves exactly like you seem to think "change" should have behaved - in that it fires as soon as a key is pressed to enter information into a form. $("#phone").bind('input',function);
You never defined event.
jQuery('#edit-phone1').keyup(function(){
jQuery('#edit-phone1').mask(event,this); //<-- what is event?
});
just add it
Second issue is you are treating window.mask like a jQuery plugin and it is not a plugin.
jQuery('#edit-phone1').keyup(function(event){ //<-- add event here
mask(event,this);
});

Alert when backspace is pressed inside textbox

I have a grid with three read-only columns. Whenever user goes in there and try to edit by pressing backspace, I need to alert by giving a message. I am using this script and it doesn't work? Can anyone correct me?
$(document).ready(function () {
$('#txtCode').bind('keypress', function (e) {
if (e.which == 8) {
alert('The column is read-only and is not editable');
}
}
});
instead of keypress try with keyup or keydown with .on() method:
$('#txtCode').on('keyup keydown', function (e) {
You can bind multiple events like this too.
and one more thing closing of $('#txtCode') seems to be missing });
$(document).ready(function () {
$('#txtCode').on('keyup keydown', function (e) {
if (e.which == 8) {
alert('The column is read-only and is not editable');
}
}); //<----");" this is the closing you misssed this
});
See the fiddle in action
If this is all the code you are testing, you weren't closing the function properly, annotated in my posted code. Also use keyup instead of keypress
$(document).ready(function () {
$('#txtCode').bind('keyup', function (e) {
if (e.which == 8) {
alert('The column is read-only and is not editable');
}
}); /*<-- You weren't closing your function properly*/
});
Fiddle
You do indeed need to add a return false statement to ensure the character doesn't get deleted anyway. I also took it a step further and extended jQuery with a preventKeyUsage method.
$(document).ready(function () {
$.fn.preventKeyUsage = function (key, message) {
return this.each(function () {
$(this).on('keydown', function (e) {
return (e.keyCode === key) ? (function () {
alert(message);
return false;
})() : true;
});
});
};
$('#txtCode').preventKeyUsage(8, 'The column is read-only and is not editable');
});
New Fiddle
Working code is:
Java Script Code:
$(document).ready(function () {
$('#txtCode').bind('keypress keydown', function (e) {
if (e.which == 8) {
alert('The column is read-only and is not editable');
}
});
});
Here is the updated code
<input type="text" id="txtCode" />
$(document).ready(function () {
$('#txtCode').bind('keydown', function (e) {
if (e.which == 8) {
alert('The column is read-only and is not editable');
return false;
}
});
});
Fiddle Demo
Try this
$(document).ready(function () {
$('#txtCode').on('keyup', function (e) {
if (e.which == 8) {
alert('The column is read-only and is not editable');
}
});
});
DEMO (Working on Firefox & Chrome)
$('#textbox').keydown(function(event){
if(event.keyCode == 8){
alert("Backspace not allowed..");
return false;
}
});
http://jsfiddle.net/xF9jL/1/
You are missing }); of keypress. google chrome have issues with keypress, u can try keydown instead
$(document).ready(function () {
$('#txtCode').bind('keydown', function (e) {
if (e.which == 8) {
alert('The column is read-only and is not editable');
}
});
});
To use delete ,arrows, backspace keys in Chrome you must use keydown. keypress on these keys work only in Firefox and Opera.
DEMO
You can probably solve the underlying issue by either not using an element that accepts input, or by using the disabled attribute:
<textarea name="example" disabled>Some text</textarea>
If you are posting back to the sever, you should assume the user has edited the field, no matter what you do to prevent it.
keypress event won't give keycodes for all keys in all browsers . Better use keyup or keydown event which gives keycode for all keys in all browsers
In order to understand the difference between keydown and keypress, it is useful to understand the difference between a "character" and a "key". A "key" is a physical button on the computer's keyboard while a "character" is a symbol typed by pressing a button. In theory, the keydown and keyup events represent keys being pressed or released, while the keypress event represents a character being typed. The implementation of the theory is not same in all browsers.

Preventing ckeditor to display character on keypress

I have a CKEditor 3.0 instance 'editor' and on its 'key' event a listener is attached so that when that function is returning false it should not type that key character on editor, that is if key 'k' is pressed it should not be displayed on the editor if the function is returning false
editor.on('key', function(e)
{
alert(""+e.data.keyCode);
return false;
});
I used above code for this but it is not working, means the character is getting typed on the editor
Trying the same using a plugin where on keypress of keycode 65 the other language character should show up instead of english language character.
CKEDITOR.plugins.add( 'typing',
{
init: function( editor )
{
editor.addCommand( 'insertcharacter',
{
exec : function( editor )
{
alert(editor.id);
alert(editor.name);
editor.on('key', function(e)
{
alert("Hello"+e.data.keyCode);
if(e.data.keyCode == 65)
{
editor.insertText('Other Language Character');
}
return false;
});
}
});
can u suggest me any solution for this.
Thanks
found the answer recently. this worked for me in the latest version(4.x).
editor.document.on('keypress', function(e) {
e.data.preventDefault(); // this will prevent the default action for any event
//your code goes here
});
In v4 you can use editor.on('key') and cancel() the event when the appropriate key is pressed.
So to ignore k keypresses,
editor.on('key', function(evt) {
var keyCodeToIgnore = 'K'.charCodeAt(); // Upper case K. Only one k key.
var pressedKeyCode = evt.data.keyCode;
if ( pressedKeyCode === keyCodeToIgnore ) {
evt.cancel();
}
}
(That wouldn't prevent 'k's being added by other means, of course, such as pasting.)
See http://docs.ckeditor.com/#!/api/CKEDITOR.editor-event-key
You can also configure the editor to block specified keystrokes. Using that you can specify case. So to ignore k and not K:
config.blockedKeystrokes = [75]; // To ignore k and K: [75, 107]
Though you'd probably want to keep the default blockedKeystrokes as well.
See http://docs.ckeditor.com/#!/api/CKEDITOR.config-cfg-blockedKeystrokes
The first method lets you do other stuff of course. You could drive people crazy by ignoring a 'u' if the previous keypress was a 'q', for example.
use following code before return from function to Cancel/block the character/event.
e.cancelBubble = true;
e.returnValue = false;
e.cancel();
e.stop();
return false;
where e is in parameter of function
I came looking for a way to bind something to the the enter key press. Except I'm using contenteditable div tags, and maybe that made the above solutions not work for me.
However I came to this, that seems to be working perfectly
$(function () {
CKEDITOR.instances['<the DOM ID of your element>'].on('key', function (e) {
if (e.data.keyCode === 13) {
//yeet
e.cancel();
}
});
});

Categories