Submit form on press of specific key - javascript

Is there any way how to submit form when you press some predefined key on your keyboard (for example ; key)? I was thinking about something with onkeypress, but dont know how to set it just for one specific key.

Yes, and you were right with thinking onkeypress, just pass in the event, and check which key is pressed with event.which:
function keyPressed(event) {
if (event.which == 186) //keycode for semi-colon
console.log("Semi-colon pressed!");
}
}
Now just attach this function to a keypress handler.
Edit: Got the keycodes from here: http://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes

You'll want to get the keycode and submit the form if it's the right keycode.
To get the keycode from an event, do:
$(document).on("keypress", function(event) {
var keyCode = event.keyCode;
var keyWhich = event.which;
if(keyCode = 'yourkey' || keyWhich = 'yourkey') {
$(form).submit();
}
});
For a full list of keycodes to replace 'yourkey' with, I'd recommend something like this cheat sheet. Just type your key in the input and use whatever value it provides as your function's logic

You can do this in jQuery:
$(document).ready( function() {
$(document).keydown(function(e){
if (e.keyCode == 186) { // ; key
$('#theform').submit();
}
});
});
See fiddle.

Related

don't can use Enter key from textarea

In my project I need diable Enter key for some textbox , because i don't want post page when enter key button . I use this Code for disable Enter key :
$(document).keypress(
function (event) {
if (event.which == '13') {
event.preventDefault();
}
});
Its work fine , but when Add textarea in page , I cant enter key for break line , because Enter key disabled .
how can I enable Enter key for textarea?
I don't know if its recommended to attach a global keypress handler like that. Regardless, the easiest way out would be
$(document).on('keypress',
function (event) {
if (event.which == '13' && event.target.tagName != 'TEXTAREA') {
event.preventDefault();
}
});
In the above, you are checking the tagName of event.target to see if the element in which the enter occured is a textarea or not
However, I would recommend this approach
$('form').on('keypress', 'form',
function (event) {
if (event.which == '13') {
event.preventDefault();
}
});
This will target all input elements and not textarea elements,
You should bind your form to detect the Enter key as,
$('#formid').on("keyup keypress", function(e) {
var code = e.keyCode || e.which;
if (code == 13) {
e.preventDefault();
return false;
}
});
Here is a demo
By this you will be able to use the Enter key on your text area without submitting the form.

Get the key that was down while a double click was made in javascript

I would like to know what key was downed (held and pressed) while a double click event was fired on an element.
The event handler allows me to get alt, shift, meta and ctrl key. What if I want to detect whether 'x' was downed when a double click was made... Or any other letter or number for that matter.
If you want to detect ctrl, alt or shift keys, they are exposed on the event object that is passed to you.
$(document).on('dblclick', function(e){
/*
* here you could use e.altKey, e.ctrlKey and e.shiftKey - all of them
* are bools indicating if the key was pressed during the event.
*/
});
If you want to detect a different key, then omar-ali's answer seems to be the right thing to do.
You must store the keycode until the keyup event, and reference the current value at the time of the double-click event.
var heldKey;
$(document).on({
'keydown' : function(e) {
heldKey = e.which || e.keyCode;
},
'keyup': function(e) {
heldKey = undefined;
},
'dblclick': function(e){
console.log(String.fromCharCode(heldKey));
}
});
One possibility is to do this, 88 = the letter x.. but.. is there a better way.
$(document).on('keydown','body',function(e) {
//console.log(e.keyCode);
if(e.keyCode==88)
keyed = true;
});
$(document).on('keyup','body',function(e) {
if(e.keyCode==88)
keyed = false;
});
$(document).on('dblclick','body',function(e) {
if(keyed==true)
alert('yes');
keyed=false;
});

How to fire the actual "Enter" keypress event of the browser?

I know it is possible to use JQuery.Event to simulate "Enter" keypress. Something like this does that -
var event = jQuery.Event( "keydown" );
event.keyCode = 13
$("input").trigger( event );
However, this does not fire the browser default behavior when the actual "Enter" key is pressed. For example, going to next line if the cursor is in textarea or submitting the form when the cursor is in input tag.
I want to know if it is possible to trigger or simulate the actual "Enter" keypress event/behavior.
Try this : Js fiddle
var e = jQuery.Event("keypress");
e.which = 13
$("#test").keypress(function(){
alert('keypress triggered')
}).trigger(e)
Do you want some thing similar this one?
$(function(){
$(document).keypress(function(event) {
if(event.which == 13) {
console.log("Dude! You hit Enter Key!!");
}
});
});
you can use this:
$("body").delegate("input", "keypress",function(e){
if(e.which == 13){
}
}
it's work for all input .

How do I get key values in HTML/Javascript

Okay, so i understand how to get the key value while using an input field... but I am taking about key values that are pressed while your browser isn't focused in any text box or text area.
I am trying to make a onscreen keypad that has buttons for 0, 1, 2, .. 9... however I want the user to be able to press the buttons with the keys on the keyboard.
I've seen this done in some websites, where if you press the S key on the homepage, it will take you to the signin screen. Facebook also does the L key, to like a photo.
So the question is: How do I get the key values in javascript, when the cursor isn't focused.
If you are using JQuery you just add the event handler to the document...
$(document).keypress(function(event) {
alert('Handler for .keypress() called. - ' + event.which);
});
(From http://forum.jquery.com/topic/how-to-catch-keypress-on-body)
Edit for zzzzBov's comment...
From the JQuery KeyPress documentation:
To determine which character was entered, 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 character code.
you need to use window.onkeydown and then check for the keys you're interested in.
https://developer.mozilla.org/en-US/docs/Web/API/window.onkeydown
You should listen on key press event.
document.onkeypress = function(evt) {
evt = evt || window.event;
var charCode = evt.which || evt.keyCode;
alert("Character typed: " + String.fromCharCode(charCode));
};
For more info Look here Link
You need to add an event listener to the window. Then in the event handler, you get the keyCode property from the passed-in event. KeyCodes are semi-arbitrary in that they don't directly map to what you might think, so you have to use a table (first result on google: http://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes) to identify the keycodes you care about.
window.addEventListener('keypress',function (evt) {
switch (evt.keyCode) {
case 48:
zeroKeyPressed(); break;
case 49:
oneKeyPressed(); break;
...
}
}, false);
You would use a key press event.
Here's an example for your usage:
window.addEventListener('keypress', function (event) {
var key_code, key;
event = event || window.event; // IE
key_code = event.charCode || event.keyCode || event.which || 0;
key = String.fromCharCode(key_code);
// prevent keys 0-9 from doing what they normally would do
if (key_code >= 48 && <= 57) {
event.preventDefault();
alert('The user pressed ' + key);
}
}, false);
Using plain js, you can use this in your layout.htmlcs, at the beginning:
#{
<script>
sessionStorage.setItem("ProductionHostURL", '#System.Configuration.ConfigurationManager.AppSettings["ProductionHostURL"]');
</script>
}
<!DOCTYPE html>
Then in your main js file of the layout.htmlcs, you can use this a method liked this:
var urlBaseProduction;
var urlBaseDevelopment;
$(document).ready(function () {
configureHostEnvironment()
....
}
In that method, configure the variables to use in production and development, like this:
function configureHostEnvironment(){
HOST = sessionStorage.getItem("ProductionHostURL")
if (HOST.length <= 0) {
alert("Host not configured correctly")
} else {
urlBaseProduction= host + '/api/';
urlBaseDevelopment= host + port + '/api/';
}
}
If you have a suggestion or improvement to this method, please comment.

action by key press

I'm designing a web based accounting software. I would like to open the "new accounting document" whenever the user press N key for example. And open "settings" whenever he/she is pressing S key.
I saw some scripts based on JavaScript and jQuery. But they did not work exactly. Can anyone help me please ?
I have tried this script:
var code = (e.keyCode ? e.keyCode : e.which);
if(code == 13) { //Enter keycode
//Do something
}
$(document).bind('keyup', function(e){
if(e.which==78) {
// "n"
}
if(e.which==83) {
// "s"
}
});
To prevent if an input is focused:
$("body").on("focus",":input", function(){ $(document).unbind('keyup'); });
$("body").on("blur",":input", function(){ $(document).bind('keyup', function(e){ etc.... });
You might want to put the bind function into its own function so you don't duplicate code. e.g:
function bindKeyup(){
$(document).bind('keyup', function(e){
if(e.which==78) {
// "n"
}
if(e.which==83) {
// "s"
}
});
}
$("body").on("focus",":input", function(){ $(document).unbind('keyup'); });
$("body").on("blur",":input", function(){ bindKeyup(); });
You can detech keypresses in jQuery using either .keypress() or .keyup() methods, here is a quick example :
$(document).keyup(function(event) { // the event variable contains the key pressed
if(event.which == 78) { // N keycode
//Do something
}
});
Here is a list of keycodes : http://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes
Update 1
.keyup and .keydown have different affects - as per comments from #ThomasClayson -: keyup is the best one to go for as keypress will repeat if the key is held down. it registers an event for each character inserted. It also doesn't register modifier keys such as shift (although not necessary here, it might be something to keep in mind)
Update 2
This is from the jQuery keyup doc site :
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. This
code corresponds to a key on the keyboard, including codes for special
keys such as arrows.
Affectively meaning that which.event is all you need to determine which key has been used. Thanks #nnnnnn
You need to read up on the .keyCode() attribute of the event object. You can interrogate that to discover which key was pressed and act accordingly. I'd also suggest you add modifier keys to your shortcuts, such as Shift or Alt, so that when someone is innocently typing in an input, the panel doesn't pop up. In the example below I've used Shift
$(document).keyup(function(e) {
if (e.shiftKey) {
switch(e.keyCode ? e.keyCode : e.which) {
case 78: // N pressed
myNPressedHandler();
break;
case 83: // S pressed
mySPressedHandler();
break;
}
}
}
$(document).bind('keypress', function(e) {
var keycode= (e.keyCode ? e.keyCode : e.which);
if(keyCode==78) {
// "n"
}else if(keyCode==83) {
// "s"
}
});

Categories

Resources