Forbidding Apostrophe while typing in HTML textBox - javascript

I am looking for a simple maybe JS to forbid apostrophe onKeyUp or OnKeyPress kind of thing. For ex, every time user presses a key if it was apostrophe (Jame's Pizza) replace it with space. I don't want to process it in PHP
I found a code but it ties the JS to the textfield Name which I don't want. I need something global,

It's always better to prevent the keystroke than to retroactively delete it. To accomplish this, you need to intercept the keypress event (keyup is too late):
document.getElementById('yourTextBoxID').onkeypress = function () {
if (event.keyCode === 39) { // apostrophe
// prevent the keypress
return false;
}
};​
http://jsfiddle.net/TSB9r/
If you only want to stop the ' from appearing in the box but would like the keypress event to propagate to parent elements, replace the return false; with event.preventDefault();. (suggested by Eivind Eidheim Elseth in the comments)

Please find below functions. It grabs all of the input elements on the page and assigns keydown and keyup event handlers to each of them. If they detect an apostrophe, it will call the preventDefault() method..
function listen(event, elem, func) {
if (elem.addEventListener) return elem.addEventListener(event, func, false);
else elem.attachEvent('on' + event, func);
}
listen('load', window, function() {
var inputs = document.getElementsByTagName('input');
for (var i = 0; i < inputs.length; i += 1) {
keyHandler(i);
}
function keyHandler(i) {
listen('keydown', inputs[i], function(e) {
if (e.keyCode === 222) { // 222 is the keyCode for apostrophe
e.preventDefault();
}
});
listen('keyup', inputs[i], function(e) {
if (e.keyCode === 222) { // 222 is the keyCode for apostrophe
e.preventDefault();
}
});
}
});

Related

on down arrow KeyPress, click event is getting fired

on down arrow keypress , click event is getting fired, event.keycode is undefined
$(".dropdown:not(.li-search) a.dropdown-toggle", ".navbar-collapse").on("click", function(event) {
var target = $(this).attr("target");
if (event.keyCode !== '40'){
if (!$(".li-menu").is(":visible") && target === undefined) {
location.href=this.href;
} else {
window.open(this.href, '_blank');
}
}
});
in this code i am trying to open main menu in new tab , but external link is getting open on down arrow keypress
call preventDefault() function.
$(".dropdown:not(.li-search) a.dropdown-toggle", ".navbar-collapse").on("click", function(event) {
event.preventDefault();
var target = $(this).attr("target");
if(event.keyCode!=='40'){
if (!$(".li-menu").is(":visible") && target===undefined) {
location.href=this.href;
}
else {
window.open(this.href,'_blank');
}
}
});
See the keycode for the reference https://css-tricks.com/snippets/javascript/javascript-keycodes/
in order to configure your app for particular key event
Looking at the classes dropdown-toggle, navbar-collapse, I'm guessing that you are using Bootstrap library.
If that is the case, the behaviour you are seeing is reasonable. Let's break down the issues:
on down arrow keypress , click event is getting fired
Q: You have only bind the handler on click event so why are it is being triggered on keypress?
A: Because this is a feature of bootstrap dropdown. To have better accessibilty, bootstrap triggers click event on the keydown of up, down, esc and space keys.
event.keycode is undefined
Since it is a click event handler and not some keyboard event handler like keydown or keypress, event.keyCode should be undefined
Note: You are using a strict equality in the following condition
if (event.keyCode !== '40')
This will check both the type and value of the operands. Now, event.keyCode always return a Number while '40' is a string, hence the above condtion will yield false even if keyCode is 40. You should correct it to:
if (event.keyCode !== 40)
Now, if you want to stop the redirect on down key, you should check whether the event triggered is an original event or was triggered by some js logic. For this, you may choose jQuery's event.isTrigger or event.originalEvent
Here's a code snippet:
$(".dropdown:not(.li-search) a.dropdown-toggle", ".navbar-collapse").on("click", function(event) {
var target = $(this).attr("target");
// Check if NOT an triggered event
if (!event.isTrigger) {
if (!$(".li-menu").is(":visible") && target === undefined) {
location.href = this.href;
} else {
window.open(this.href, '_blank');
}
}
});
<a> tags will fire the click event when you press enter on them. However you will not have a keyCode on the event because it is not a Key* event. If you want to know the keyCode add a keyDown or keyUp handler as well. You could also handle both by doing something like the following:
$(".dropdown:not(.li-search) a.dropdown-toggle", ".navbar-collapse").on("click keydown", function(event) {
var target = $(this).attr("target");
if(event.type === 'keydown' && event.keyCode!=='40'){
if (!$(".li-menu").is(":visible") && target===undefined) {
location.href=this.href;
}
else {
window.open(this.href,'_blank');
}
}
});
You'll probably also want to add an event.preventDefault(); in there if you wish to prevent default browser behaviour from taking place.

Use a preventdefault to get out of the loop after pressing Enter key

This is a complete revision of my initial question, all unnecessary resources and references were deleted
I am tying the same event listener to 2 different elements: a button and Enter key, and it looks like the following:
var funcelement = function(){
//function code
};
$('#buttonID').click(funcelement);
$('#inputID').keyup(function () {
if (event.which == 13) {
$('#buttonID').trigger('click');
}
})
What I am trying to do is to prevent propagation of the enter key press if focus is on the submit button(#buttonID) by using preventDefault().
So I tried various combinations to make it work. The following is the latest result on my attempts
$('#inputID').keyup(function () {
var hasfocus = $('#buttonID').is(':focus') || false;
if (event.which == 13) {
if (!hasfocus) {
event.preventDefault();
$('#buttonID').trigger('click');
//hasfocus = true;
}
else {
//event.preventDefault();
//$('#buttonID').trigger('click');
}
}
})
After I enter a text into an input box and press Enter key, a confirmation window with yes/cancel buttons pops up with focus on yes button. Once I press Enter again, another window confirming that changes were made pops up with Ok button focused on it. Once I press Enter again, everything I need is being made.
However, there is one problem: after the last step is done, I am going back to the if (!hasfocus) line.
How do I prevent that from happening? Once the stuff I need is done - I don't want to go into that line again.
You can pass a parameter to into the function and stop the propagation there like so:
var funcelement = function(event, wasTriggeredByEnterKey){
if (wasTriggeredByEnterKey && $('#buttonID').is(':focus')) {
event.stopPropagation;
}
//function code
};
$('#buttonID').click(funcelement);
$('#inputID').keyup(function () {
if (event.which == 13) {
$('#buttonID').trigger('click', [true]);
}
}
)
UPDATE
In order to answer your revised issue, you should use the "keydown" event rather than "keyup" when working with alerts. This is because alerts close with the "keydown" event but then you are still triggering the "keyup" event when you release the enter key. Simply change the one word like this:
$('#inputID').keydown(function () {
var hasfocus = $('#buttonID').is(':focus') || false;
if (event.which == 13) {
if (!hasfocus) {
event.preventDefault();
$('#buttonID').trigger('click');
//hasfocus = true;
}
else {
//event.preventDefault();
//$('#buttonID').trigger('click');
}
}
})

Restore default value of arrows key

I'm using a script (impress.js) that bins some particular action to keyup and keydown events for left, right, up and down arrows.
In some particular moments (for example while typing in a textarea) I want back the default behaviour for the arrows.
I tried without success with
$("a#show-ta").click( function() {
document.addEventListener("keydown", function ( event ) {
if (event.keyCode >= 37 && event.keyCode <= 40) {
return;
}
});
document.addEventListener("keyup", function ( event ) {
if (event.keyCode >= 37 && event.keyCode <= 40) {
return;
}
});
});
where a#show-ta is the button that shows my textarea.
You want to prevent the keypress from bubbling up to the document where (I assume) Impress binds its handlers:
$("textarea").on('keyup keydown keypress', function(e) {
e.stopPropagation();
});
If you need the event in a specific zone, such as a texarea, you should stop the propagation of the event like this :
$('textarea').keydown( function(ev) {
ev.stopPropagation();
});
If the events are necessary for the whole page but you want to exclude while you are in a textarea, for example, you could raise a flag which you would validate in the event.
var keydownActivated = true;
$('textarea').keydown( function(ev) {
if (keydownActivated) {
ev.preventDefault();
// dostuff
}
});
This will more or less get you where you are going. Create a flag that tracks whether or not the textarea has focus, and check that flag in your current key press event handlers. I can't see all of your code, so this is just a simple example:
var textareaHasFocus = false;
var textarea = document.querySelector('#yourTextarea');
textarea.addEventListener('focus', function(event) {
textareaHasFocus = true;
}, false);
textarea.addEventListener('blur', function(event) {
textareaHasFocus = false;
}, false);
document.addEventListener("keydown", function ( event ) {
if (textareaHasFocus) return true;
// your current keyboard handler
});
document.addEventListener("keyup", function ( event ) {
if (textareaHasFocus) return true;
// your current keyboard handler
});

the shift key is just ignored after another key has been depressed, poor shift key. How do I detect when it is released?

I have a text input, that presently goes transparent when a user presses shift (keydown) and binds a listener for the shift key going up
ie.
$('#foo').keydown(function(){
if(event.which==16){
//make #foo transparent
$(this).keyup(function(){
if(event.which==16){
//return #foo to its former glory
$(this).unbind('keyup');
}
});
};
})
This works fine when no characters are pressed in the interim between depressing and releasing the shift key. The problem is that when shift is down and another character is pressed, the shift key seems to have been completely forgotten about. When the shift key is released, no keyup fires.
I tried triggering a 'fake' keydown with the .which property set to 16, to nudge it in the right direction after other characters are pressed, but to no avail.
Any suggestions would be greatly appreciated!
While pressing shift, it will continuously trigger keydown events until you release it, so your example will bind as many keyup handlers as there are keydown events triggered. This will most likely cause all kind of weird problems.
Instead, bind both keydown and keyup to the same handler and do your magic in there:
$("#foo").on("keydown keyup", function (e) {
if (e.which === 16) {
if (e.type === "keydown") {
// make #foo transparent
} else {
// return #foo to its former glory
}
}
});
See test case on jsFiddle.
However, if you lose focus of the input while pressing shift and then release, it will not work as expected. One way to solve it is to bind to window instead:
var $foo = $("#foo");
var shiftPressed = false;
$(window).on("keydown keyup", function (e) {
if (e.which === 16) {
shiftPressed = e.type === "keydown";
if (shiftPressed && e.target === $foo[0]) {
$foo.addClass("transparent");
} else {
$foo.removeClass("transparent");
}
}
});
$foo.on("focus blur", function (e) {
if (e.type === "focus" && shiftPressed) {
$foo.addClass("transparent");
} else {
$foo.removeClass("transparent");
}
});
See test case on jsFiddle.

Jquery: Executing a function on keypress on google.com

I am trying to capture the search query from google.com when the "enter" key is pressed.
I am using the following code to test that the event is actually being triggered:
$(document).keypress(function(e) {
if(e.which == 13) {
alert('You pressed enter!');
}
});
This does not work when the focus is in the query box, but works fine otherwise I assume this is because an event is not being bubbled up by the auto-complete JS? Any ideas what might be happening, and how I can get the keypress event to fire when the focus is on the query box, which is the case when a query is being entered?
You can try $(window).on('keyup', function() {}); of you can bind the same handler to the search input.
Use "hashchange" event
It is triggered when triggered "auto-complete JS"
$(window).on("hashchange", function() {
var query = getKeywordsFromUrl(document.location.href);
} );
function getKeywordsFromUrl(href) {
var reStr = "google.com/search.*[&?]q=(.*?)(&.*)?$";
var rx = new RegExp(reStr, 'm');
if (rx.test(href)) {
var parts = rx.exec(href);
if (parts[1]) {
var terms = decodeURI(parts[1]).split("+");
return terms;
}
}
return null;
}

Categories

Resources