jQuery keypress to work normally except hitting enter - javascript

I would like to trigger a click if enter is pressed inside an input tag, but would like to have the default event strategy in all other cases. I have tried it this way:
$("#keywords").keypress(function(e) {
if (e.charCode === 13) {
$("#campus-search").click();
} else {
$("#keywords").val($("#keywords").val() + String.fromCharCode(e.charCode));
}
});
It works, but I am still not satisfied, because when I click inside the input somewhere in the middle of text or press the left button, or home button and then try to type some text, it will show it at the end of the input, which is bad user-experience. Can I keep the input to work in the default way except the case when enter is pressed?

I think what you are looking for is this:
$(document).ready(function () {
$("#test").keyup(function (event) {
if (event.keyCode == 13) {
$("#campus-search").click();
}
});
$("#campus-search").click(function () {
console.log("BUTTON IS CLICKED");
});
});
The input will act completely normal and everything works on default, unless when you press the enter button (keyCode = 13), then the button .click() event will be triggered.
Working Fiddle: http://jsfiddle.net/Mz2g8/3/
————
# Update: Just one hint for the code in your question, do not use charCode, as it is deprecated.
This feature has been removed from the Web. Though some browsers may still support it, it is in the process of being dropped. Do not use it in old or new projects. Pages or Web apps using it may break at any time.
(E.g. charCode does not work with FF v29.0.1)
And something different but important to know:
charCode is never set in the keydown and keyup events. In these cases, keyCode is set instead.
Source: https://developer.mozilla.org/en-US/docs/Web/API/event.charCode

This should work
$("#keywords").keypress(function(e) {
if (e.charCode === 13) {
e.preventDefault(); // prevent default action of the event if the event is keypress of enter key
$("#campus-search").click();
} else {
$("#keywords").val($("#keywords").val() + String.fromCharCode(e.charCode));
}
});

I think you can eliminate the else clause entirely to get your desired result.
Look at this jsfiddle.

The keypress function does not capture non-printing keys, such as shift, esc, delete, and enter, so the best way to go about this would be have two event handlers: one for keypress, as you have defined above, and one for keydown that checks for the charCode 13 and then performs the click() event on $(#campus-search) if that keycode is passed (by an enter press).
Demo

This is what you are looking for:
HTML:
<input id="keywords" type="text" value="" />
<input id="campus-search" type="button" value="Campus Search" />
JavaScript / jQuery:
$("#keywords").keypress(function (e) {
if (e.charCode === 13) {
$("#campus-search").click();
} else {
$("#keywords").val($("#keywords").val() + String.fromCharCode(e.charCode));
}
});
$("#campus-search").on("click", function () {
alert("Searching..");
});
Live Demo

Related

use Jquery to set focus to input with keydown

I am using a site that has a search box and I would like it so when you press the space bar but don't have the search text box selected, the search text box gets focus and has it's text cleared. I have it about done, but the check to see if the search box has focus isn't functioning properly. Any suggestions on my code? As is, if you press the space bar, it clears the search box, even if you're typing in the search box.
document.addEventListener('keydown', function (event) {
if (event.keyCode == 32) {
if ($('#searchTextBox').not(':focus')) {
$("#searchTextBox").focus().select();
}
}
});
While you delegate a keydown event on the document, you can also check if the source/target is the textbox itself by using event.target. If the event comes from the text field, just ignore it.
$(document).on('keydown', function (event) {
if (event.which == 32 && event.target.id != 'searchTextBox')
$("#searchTextBox").focus().select();
});
Working example : https://jsfiddle.net/DinoMyte/mdu5fxkq/3/
Maybe this will work
$(document).ready(function(){
$(document).on('keydown',function(event){
if(event.keyCode==32){
if(!$('#search').is(':focus')) {
$('#search').focus().select();
}
}
});
});
Grettings!
Even Simpler
Check for the keyCode as 32 is for spacebar and you can use any other by using its code
$(document).on('keydown', function (event) {
if (event.keyCode== 32) {
$("#searchTextBox").focus().select();
}
});

Event listener doesn't work for Enter key

What may be the reason, that event listener of Enter key doesn't work?
I tried both plain JS:
addEventListener("keydown", function (e) {
if (e.keyCode === 13) {
enter(e);
}
});
function enter(e) {
event.preventDefault();
alert("You pressed enter");
}
and jQuery:
$(document).keypress(function(e) {
if(event.which == 13) {
event.preventDefault();
alert('You pressed enter!');
}
});
Also, I tried both event and e. Doesn't work. For another key, for example Backspace it works well.
That is a plugin for our corporate intranet - when you click some letter in email inbox, and after that press Enter, small pop-up window must be shown. But for some reason Enter is ignored in my script - instead of showing pop-up, webpage immediately opens the letter (that is a default behavior).
As I understand, the reason may be in another listener somewhere in webmail interface? Or not? If yes, may I somehow impart higher priority for handling Enter (so, before opening the letter, pop-up will be shown)?
Apologize for long description.
It should work as long as you bind the event handler within the document.ready
$(function(){
$(document).keypress(function(e) {
if(event.which == 13) {
event.preventDefault();
alert('You pressed enter!');
}
});
});
Here is a working sample

How can I use the KeyDown event with the exception of backspace?

I have a file with multiple inputs. I have a Javascript function which writes information about the input and I do not want it triggered when the user is pressing backspace.
EDIT: Question: Why does this code not work in terms of preventing backspace execution? Instead the entire function does not work:
function hide_words(z,x)
{
if(event.key == 8)
{
event.preventDefault();
}
document.getElementById(z).innerHTML = x;
}
The above just stops the functioning from executing all together.
Update this to:
function inputOn(event)
{
if(event.keyCode == 8)
{
event.preventDefault();
}
}
document.getElementById("input").addEventListener("keydown", inputOn, false);
<input id="input" style="width: 400px;" value="try to delete any text using backspace." />
preventDefault will cancel out the normal action. So the backspace won't do a thing. A keyDown is cancelable, so this works. Please note that the input of other keys is still possible.
You might also want to catch keyCode 46 which is the delete button.

form should not submit on enter if focus is not on submit button

I have a requirement where user cannot submit the form if he press enter key unless focus will be on submit button.
Using following code, I am able to do that, but now the issue is, if I have any enter key event attached specific to any field (e.g. if I want to attach enter key event to one textfield for some special requirement), it is not allowing me due to the script I have written below..
<script>
$(document).keydown(function(event) {
if (event.keyCode == 13) {
var $focusedItem = $(document.activeElement);
if($focusedItem.is("button") || $focusedItem.is("a") || $focusedItem.attr("type") == "submit") {
$focusedItem.click();
}
else {
event.preventDefault();
}
}
});
</script>
Any solution where I can restrict user from submitting form on pressing enter key, if focus is not on the submit button but at the same time if there will be any enter key event attached to any form-field, that should also work.
If you had created a JsFiddle it would be easier to help. However, I'm thinking you should do something like this:
if($focusedItem.attr('id') == 'submitButton') {
if (event.keyCode == 13) {
submit the form
}
}else if ($focusedItem.attr('id') == 'Anothertextarea') {
if (event.keyCode == 13) {
do something special
}
}else{
if (event.keyCode == 13) {
return null;
}
}
Remove the line event.stopPropagation(); from your script, you need only the preventDefault() (prevents the submit).
When you do stopPropagation() you are stopping all other keypress events on the element.
Try that and see if it fits your needs:
--DEMO--
$(document).on('submit', 'form', function (e) {
e.preventDefault();
}).on('click', ':submit', function (e) {
if (!$(document.activeElement).is(':submit')) return;
var form = $(this).closest('form').length ? $(this).closest('form')[0] : $('#' + $(this).attr('form'))[0];
form.submit();
});
Maybe I'm missing the point, this is basically a standard html issue.
Don't give the form an submit action (move it to a click event directly on the button) and change all button types to button instead of submit.
I can't remember if simply removing the submit from the form is enough. If not then just do onSubmit="return false;" I think that does it.
However as a note the requirement for this as a global behavior is probably wrong and if its for the government then you will probably get in trouble since its not compliant with accessibility guidelines.

Esc key not getting recognized in Firefox

For some reason this script isn't working in Firefox:
document.onkeydown=function keypress(e) {
if (e.keyCode == 27) {
window.location = "/edit"
};
};
It works fine in Chrome, but for some reason it's not working in Firefox.
Basically, what it does is load the /edit page when you press the escape key.
use:
document.onkeydown=function keypress(e) {
e=(e||window.event);
if (e.keyCode == 27) {
try{e.preventDefault();}//Non-IE
catch(x){e.returnValue=false;}//IE
window.location = "/edit";
};
}
The default-action for ESC is to stop loading the page,
so you must prevent from this behaviour, otherwise you cannot change the location.
Fiddle: http://jsfiddle.net/doktormolle/CsqgE/ (Click into the result-frame first before using ESC)
But however, you really should use another key.
A user expects that the loading of the current page stops if he uses ESC , nothing else.
The event handler is working for me: http://jsfiddle.net/Tm2PZ/
I suspect the lcoation you're setting is not valid.
Try setting window.location.href instead.
if you don't use 'Escape keyup or Escape keydown' for other things in your code, you can use 'keyup' to replace keypress**
document.body.addEventListener( 'keyup', function (e) {
e=(e||window.event);
if (e.key == "Escape") {
console.log('escape is pressed');
}
},false );
e.keyCode is depreciate, use e.key, add "console.log(e.key)" in your listener if you want to get key name
it is better, because it adapts to the keyboard which does not have the same composition and e.keyCode does not adapt

Categories

Resources