How to Exclude Child Element from jQuery Event Handler? - javascript

I am modifying an existing web page. I added a <textarea> to the page, but found that the Enter key doesn't work as expected.
After spending considerable time searching, I found the following:
$('form').keypress(function (e) {
if (e.keyCode == 13)
return false;
});
I need to leave as much as much of the existing functionality in place as I can. But I need to disable this for my <textarea>. (It appears mine is the only <textarea> on the page.
But how can I do this? I thought about adding .not('textarea') to the selector above. But that doesn't work because the handler is on the form, which is not a textarea.
I can I exclude <textarea>s from the filter above?

jsBin demo
You can simply target the inputs
$('form input').keypress(function (e) {
if (e.which == 13) e.preventDefault(); // Don't misuse return false
});
the textarea will go on with the enter key as usual
Depends on the use-case.
If you want to be sure nothing brakes use:
$('form *:not(textarea)').keypress(function (e) {
if (e.which == 13) e.preventDefault();
});
where * targets every children, and :not selector excludes the desired one.
here's another example:
$('form *').keypress(function (e) {
if (e.which == 13 && this.tagName!=="TEXTAREA") e.preventDefault();
});

You can check the if the target is the textarea :
$('form').keypress(function (e) {
if($(e.target).is('textarea')) return;
if (e.keyCode == 13)
return false;
});

Add a filter inside your function like this
$('form').keypress(function (e) {
if (e.keyCode == 13 || e.target.tagName.toLowerCase() == 'textarea')
return false;
});

the simplest way is to use on(), so you don't need to do any extra element comparing inside the event handler:
$('form').on("keypress", ":not(textarea)", function (e) {
if (e.keyCode == 13)
return false;
});
you use on() to watch the form, and the css selector to avoid textareas.
to easily tweak later, you can blacklist other elements by tagname or class using more :not() operators sperated by commas. plus, on() is now recommended over the older single-purpose handlers anyway.

Related

No alert when input is entered

I am trying to get it so that when I press enter while focused on an input, it alerts something.
I have an input tag,
<input></input>
Then I have javascript,
document.getElementsByTagName("input").keyup = function(e) {
if (e.keyCode == 13) {
alert("1111");
}
};
Why is this not working? Here is my codepen: http://codepen.io/darkfyi/pen/meBdzZ.
There are two problems with your code:
The document.getElementsByTagName method returns a HTMLCollection, so you must iterate through this collection, or use the first item by using [0].
If you want to delegate the event keyup by its property, you should use .onkeyup = function() {, as there is no HTMLInputElement.keyup method. You would use keyup in addEventListener method, for example.
So, your code should be something like:
document.getElementsByTagName("input")[0].onkeyup = function(e) {
if (e.keyCode == 13) {
alert("1111");
}
};
Updated codepen.

Restricting user from entering specific character in dynamically generated textboxes

I am trying to prevent user from entering two specific characters in any of the textboxes on the page. The code I am using does not work with dynamically appended textboxes.
DEMO
window.onload = function () {
$("input").keypress(function (e) {
if (e.which === 44 || e.which === 124) {//preventing , and |
e.preventDefault();
}
});
}
And since I am not using server controls I can not use ajax filter etc. I would like to have a simple solution to this. Without causing any conflicts in the code. Thank you.
Try to use event-delegation in this context, since you need to bind events for the elements which are being appended at the run time.
$(document).on('keypress',"input",function (e) {
if (e.which === 44 || e.which === 124) {
e.preventDefault();
}
});
Side Note: I just use document for delegating the event, but you should probably use any closest static parent to the input element, in order to attain a performance boos up.
use event delegation for dynamically created dom
$(document).on("keypress","input",function (e) {
if (e.which === 44 || e.which === 124) {
e.preventDefault();
}
});
document use immediate parent selector which is static in html
Demo: http://jsfiddle.net/4v78q/
http://jsfiddle.net/4v78q/1/
$(document).ready(function(){
$("input").each(function(){
$(this).keypress(function(e){
var keycode = e.which || e.keyCode;
if (keycode === 44 || keycode === 124) {
e.preventDefault();
}
});
});
});

jQuery to trigger CSS3 button

I have this CSS3 enter button
here:
If you click it, it seems like it's pressed. I want to achieve the same effect (probably using jQuery), by pressing the enter key physically on my keyboard.
I did something like this: (sorry if it's completely wrong, I don't do jQuery at all)
<script type="text/javascript">
$(document).ready(function(){
$("enter").keypress(function(event){
if(event.keyCode == 13){
$(this).toggleClass(".button-clicked");
}
});
});
</script>
The CSS selector for the unpressed button is:
.button and .button.orange {}
The CSS selector for the pressed button is:
.button:active, .button-clicked {}
Thanks for your help!
I haven't tested this, but I think you should be able to do something like
I have just tested this (and linked to a demo, below the jQuery), and it works pretty well:
$('body').keydown(
function(e){
if (e.which == 13) { // enter
$('buttonSelector').addClass('button-clicked');
}
}).keyup(
function(e){
if (e.which == 13) { // enter
$('buttonSelector').removeClass('button-clicked');
}
});
JS Fiddle demo.
With this the keydown causes the button to appear pressed so long as the enter key is pressed, and, on release, triggers the keyup() handler, changing the style of the button so as to appear un-clicked.
Refined the above, somewhat, using on(), though having to use an if/else if statement to check the function type:
$('body').on('keydown keyup', function(e) {
if (e.type == 'keydown') {
if (e.which == 13) { // enter
$('#button').addClass('button-clicked');
}
}
else if (e.type == 'keyup') {
if (e.which == 13) { // enter
$('#button').removeClass('button-clicked');
}
}
});
JS Fiddle demo.
References:
keydown().
keyup().
addClass().
removeClass().
on().
You are trying to apply the keypress to an <enter></enter> element (which doesn't exist), try doing this:
<script type="text/javascript">
$(document).ready(function(){
$("body").keypress(function(event){
if(event.keyCode == 13){
$(".button").toggleClass("button-clicked");
}
});
});
</script>
Close but how about this:
//bind to the `keydown` event when the `document` is focused
$(document).on('keydown', function (event) {
//if enter is pressed
if (event.keyCode == 13) {
//add the `.button-clicked` class to any element with the `.button` class
$('.button').addClass('button-clicked');
}
}).on('keyup', function (event) {
if (event.keyCode == 13) {
$('.button').removeClass('button-clicked');
}
});
Here is a jsfiddle: http://jsfiddle.net/jasper/T5yEu/2/
Notice that I added !important to the .button-clicked class on several of the rules to make sure they are added to the element.

Bind enter key to specific button on page

<input type="button" id="save_post" class="button" value="Post" style="cursor:pointer;"/>
How can I bind the enter key on the persons keyboard to this specific button on the page? It's not in a form, and nor do I want it to be.
Thanks!
This will click the button regardless of where the "Enter" happens on the page:
$(document).keypress(function(e){
if (e.which == 13){
$("#save_post").click();
}
});
If you want to use pure javascript :
document.onkeydown = function (e) {
e = e || window.event;
switch (e.which || e.keyCode) {
case 13 : //Your Code Here (13 is ascii code for 'ENTER')
break;
}
}
using jQuery :
$('body').on('keypress', 'input', function(args) {
if (args.keyCode == 13) {
$("#save_post").click();
return false;
}
});
Or to bind specific inputs to different buttons you can use selectors
$('body').on('keypress', '#MyInputId', function(args) {
if (args.keyCode == 13) {
$('#MyButtonId').click();
return false;
}
});
Vanilla JS version with listener:
window.addEventListener('keyup', function(event) {
if (event.keyCode === 13) {
alert('enter was pressed!');
}
});
Also don't forget to remove event listener, if this code is shared between the pages.
Maybe not quite what you're looking for but there is a HTML property that lets you assign a specific button called an access key to focus or trigger an element. It's like this:
<a href='https://www.google.com' accesskey='h'>
This can be done with most elements.
Here's the catch: it doesn't always work. for IE and chrome, you need to be holding alt as well. On firefox, you need to be holding alt and shift (and control if on mac). For safari, you need to be holding control and alt. On opera 15+ you need alt, before 12.1 you need shift and esc.
Source: W3Schools

How can I disabling backspace key press on all browsers?

I'm trying to disable the backspace button on an order page in all cases except when a textarea or text input is an active element to prevent users from accidentally backing out of an order. I have it working fine in most browsers, but in IE (testing in IE9, both regular and compatibility mode) it still allows the user to hit the backspace and go to the previous page.
Here's the code:
$(document).keypress(function(e){
var activeNodeName=document.activeElement.nodeName;
var activeElType=document.activeElement.type;
if (e.keyCode==8 && activeNodeName != 'INPUT' && activeNodeName != 'TEXTAREA'){
return false;
} else {
if (e.keyCode==8 && activeNodeName=='INPUT' && activeElType != 'TEXT' && activeElType != 'text'){
return false;
}
}
});
Any advice on what I'm doing wrong here?
Thanks!
I think you're overcomplicating that. Rather than checking for an active element, find the event target instead. This should give you the information you need. It's also better to use keydown rather than keypress when there is no visible character. Finally, it's better to use e.preventDefault() for better granularity.
$(document).keydown(function(e) {
var nodeName = e.target.nodeName.toLowerCase();
if (e.which === 8) {
if ((nodeName === 'input' && e.target.type === 'text') ||
nodeName === 'textarea') {
// do nothing
} else {
e.preventDefault();
}
}
});
NB I could have done this the other way round, rather than an empty if block and all the code going in the else block, but I think this is more readable.
Instead of keypress, try the keydown function, it will fire before the actual browser based hook. Also, putting in a preventDefault() function will assist in this. IE :
$(document).keydown(function(e){
e.preventDefault();
alert(e.keyCode);
});
Hope this helps.
The most Simple thing you can do is add the following one line in the very first script of you page at very first line
window.history.forward(1);
Most examples seem to be for the JQuery framework - Here an example for ExtJS
(I've been getting a lot of downvotes for this recently as the question now has JQuery tag on it, which it didn't previously. I can remove the answer if you like as isn't for JQuery but it's proven to help others not using that framework).
To use this add this code block to your code base, I recommend adding it inside the applications init function().
/**
* This disables the backspace key in all browsers by listening for it on the keydown press and completely
* preventing any actions if it is not which the event fired from is one of the extjs nodes that it should affect
*/
Ext.EventManager.on(window, 'keydown', function(e, t) {
var nodeName = e.target.nodeName.toLowerCase();
if (e.getKey() == e.BACKSPACE) {
if ((nodeName === 'input' && e.target.type === 'text') ||
nodeName === 'textarea') {
// do nothing
} else {
e.preventDefault();
}
}
});
Use e.which instead of e.keyCode; jQuery normalizes this value across browsers.
http://api.jquery.com/keydown/
To determine which key was pressed,
examine the event object that is
passed to the handler function. While
browsers use differing properties to
store this information, jQuery
normalizes the .which property so you
can reliably use it to retrieve the
key code.
Then, use e.preventDefault(); to prevent the default behaviour of moving to the previous page.
<html>
<head>
<script type="text/javascript">
function stopKey(evt) {
var evt = (evt) ? evt : ((event) ? event : null);
var node = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null);
if ((evt.keyCode == 8) && (node.type!="text")) {return false;}
}
document.onkeypress = stopKey;
</script>
</head>
<body onkeydown="return stopKey()">
<form>
<input type="TEXTAREA" name="var1" >
<input type="TEXT" name="var2" >
</form>
</body>
</html
I had to add the onDownKey attribute to the body in order to get editing keys to go to the functions.
$(document).keydown(function(e) {
var elid = $(document.activeElement).is('input');
if (e.keyCode === 8 && !elid) {
return false;
}
});
Hope this might help you
Seems like the "backspace" will also act as "navigation back" if you have selected radio buttons, check-boxes and body of document as well. Really annoying for forms - especially when using post. All the form could be lost with one slip of the "backspace" key -_- ...
Honestly... who's idea was it to allow the "backspace as a navigational "back" button!!! really bad idea in my opinion.
I disable the "backspace" default on anything that is not a text area or text field - like this:
$(document).keydown(function(e){
console.log(e.keyCode+"\n");
var typeName = e.target.type;//typeName should end up being things like 'text', 'textarea', 'radio', 'undefined' etc.
console.log(typeName+"\n");
// Prevent Backspace as navigation backbutton
if(e.keyCode == 8 && typeName != "text" && typeName != "textarea"){
console.log("Prevent Backbutton as Navigation Back"+typeName+"\n");
e.preventDefault();
}
//
})
Not sure where else one would want the normal behavior of a back-button other than in these two areas.
document.onkeydown = KeyPress;
function KeyPress(e) {
if (!e.metaKey){
e.preventDefault();
}
}

Categories