How to get keys pressed before enter with jQuery - javascript

Sorry if this question has already been asked, I am trying to create an app where the user scans a bar code and the data is then shown on the screen. I don't want to use textbox's because I don't want the data to be editable.
So far I've managed to get the enter key which is automatically sent at the end of the barcode but can't seem to get the keys pressed before, any help would be massively appreciated!
var item = "";
$(document).keypress(function(e) {
if(e.which == 13) {
alert(item);
}else{
item = item + e.which();
}
});
Just to clarify what I want to do is show an alert box with the keys pressed before enter! For example : A B C D ENTER would show an alert("ABCD")
Thanks!
UPDATE
So got my code to work but I'm getting "undefinedTHEKEYSPRESEDHERE" as the return:
var counter = 0;
var item = [];
$(document).keypress(function(e) {
if(e.which == 13) {
alert(item[counter]);
counter++;
}else{
item[counter] = item[counter] + String.fromCharCode(e.which);
}
});
Obviously this isn't clear enough, so I've outlined my problem below:
What I'm getting from alert(item[counter]);:
undefinedKEYS
What I want from alert(item[counter]);:
KEYS
So from undefinedKEYS to just KEYS I need to remove the text "undefined".
Clear enough?

Change e.which() to String.fromCharCode(e.which).
http://jsfiddle.net/8msksn3a/
var item = "";
$(document).keypress(function(e) {
if(e.which == 13) {
alert(item);
}else{
item = item + String.fromCharCode(e.which);
}
});

Not that I recommend this way of checking for previous results, but you are basically resetting item to "" inside the keypress event. Set it once outside the event.
which is a property, not a method:
Convert from ASCII to string char with string.fromCharCode (A google search would have given you that in two seconds).
Use (e.which || e.keyCode) to ensure you get the keycode on all browsers.
e.g.
var item = "";
$(document).keypress(function(e) {
if((e.which || e.keyCode) == 13) {
alert(item);
}else{
item = item + String.fromCharCode(e.which || e.keyCode);
}
});

Copy paste to your console and run:
var keys = [];
$(document).keypress(function(e) {
var keyChar;
if(e.which == 13) {
console.log( keys.join('') );
keys.length = 0;
}
else{
keyChar = String.fromCharCode(e.which);
if( keyChar )
keys.push( keyChar );
}
});
This technique will not show keys which does not have a textual character assigned to them (like the F1-F12 keys for example)

Related

Jquery capture tab + some key combination

How can I catch, for example, tab+t combination with jQuery? I've found a lot of examples with alt, shift and ctrl, since event object contains special flags in order to understand if, for example, alt was pressed. But there is not such thing for tab.
This should work. It's a bit convoluted and there is likely an easier way, but it works fine.
JSFiddle: https://jsfiddle.net/spybhhxc/
var tabdown = false;
var tdown = false;
$(document).keydown(function(e) {
if(e.which == 9) {
tabdown = true;
}
if(e.which === 84)
{
tdown = true;
}
if(tabdown && tdown)
{
//do your thing
}
});
$(document).keyup(function(e) {
if(e.which == 9) {
tabdown = false;
}
if(e.which === 84)
{
tdown = false;
}
});
This presents a problem though, as once you press tab, the document is unfocused as the tab key navigates to elements in a browser. You would be much better off using something like alt or ctrl which don't interact with the browser.
We can have a tab key pressed [tabPressed] variable which will be set to true on key down and unset the same on its key up event. We will using the tab key pressed[tabPressed] variable to check whether it is in pressed state during the other key press activities. The tab keycode is 9.
jsfiddle link http://jsfiddle.net/e3Lveyj2/
var tabPressed=false;
function handleKeyDown(e) {
var evt = (e==null ? event:e);
if(evt.keyCode == 9){
tabPressed=true;
}
if ((tabPressed) && (evt.keyCode == 84)) {
alert ("You pressed 'Tab+t'")
}
}
function handleKeyUp(e) {
var evt = (e==null ? event:e);
if(evt.keyCode == 9){
tabPressed=false;
}
}
document.onkeydown = handleKeyDown;
document.onkeyup = handleKeyUp;

changing character code with js and show the new character instead

I want to write a code that if a user press a key, It changes the keyCode or charCode of the User event and trigger the event with a new charcode,
I wrote this code in jsfiddle but this code doesn't work because of too much recursion.
function convert(e, elem) {
function getKey(event) {
if (event.which == null) {
return event.keyCode // IE
} else if (event.which != 0 && event.charCode != 0) {
return event.which // the rest
} else {
return null // special key
}
}
var key = getKey(e);
key++;
return key;
}
$(".myInput").keypress(function (e) {
var returnedKey = convert(e, this);
e.which = e.keyCode = returnedKey;
$(this).trigger(e);
});
<input type="text" class="myInput" />
any Idea that help my code work would be appreciated.
Thanks alot.
Regarding the recursion issue, you need to add a stopping condition, for example:
$(".myInput").keypress(function (e) {
var returnedKey = convert(e, this);
e.which = e.keyCode = returnedKey;
if(!e.isSecondTrigger){
e.isSecondTrigger = true;
$(this).trigger(e);
}});
This way, you only change the value once. However, as was stated by LShetty in the comments section, the event values are read only - you can't change the value of the button that was already pressed and in that way change the input text. In order to do this, you need to manually change the value of the input text after each user action (i.e. hold the value of the input text at each key press, modify it when the user presses a key, and then overwrite the input field value with the output).

How do I detect the "enter" key and "shift" key at the same time to insert a line break

I'm trying to create a note system. Whatever you type into the form gets put into a div. When the user hits Enter, they submit the note. However I want to make it so when they hit Shift + Enter it creates a line break a the point where they're typing (like skype). Here's my code:
$('#inputpnote').keypress(function(event){
var keycode = (event.keyCode ? event.keyCode : event.which);
if(keycode=='13' && event.shiftKey){
$("inputpnote").append("<br>");
}
else if(keycode == '13'){
var $pnote = document.getElementById("inputpnote").value;
if ($pnote.length > 0) {
$("#pnotes-list").append("<div class='pnote-list'><li>" + $pnote + "</li></div>");
$('#inputpnote').val('');
}
}
});
#inputpnote is the form where the user enters their note and #pnotes-list is the place where the notes are being appended to. Thank you in advance!
I think for this you'd have to set two global variables, 1 for shitftKeyPress and 1 for enterKeyPress and then you'd need a keydown and a keyup to set those values and then you check to see if they are both true, because your logic is saying, when a key is pressed, execute this code, if you press a key and then press another key, the only that will happen is the function will be called twice.
EDIT:
Example code of what it should look like:
var hasPressedShift = false;
var hasPressedEnter = false;
$('#inputpnote').keydown(function(event){
if(shiftkey) {
hasPressedShift = true;
}
if(enterKey) {
hasPressedEnter = true;
}
});
$('#inputpnote').keyup(function(event){
if(shiftkey) {
hasPressedShift = false;
}
if(enterKey) {
hasPressedEnter = false;
}
});
$('#inputpnote').keypress(function(event){
if(hasPressedShift && hasPressedEnter) {
// Do something
}
});
This was a quick mock up, but it's similar to how it should look

Replacing comma with dot Char

I have made a calculation app in AppJs.
Basicly it is a bunch of:
<input type=number>
fields.
To make it more user friendly i thought i should replace All commas with dots, so that javascript can use the actual values to calculate.
I've tried doing this with this following pice of code:
$("input[type=number]").keyup(function(e){
var key = e.which ? e.which : event.keyCode;
if(key == 110 || key == 188){
e.preventDefault();
var value = $(this).val();
$(this).val(value.replace(",","."));
}
});
In explorer 9, this works as expected: see fiddle
But since App.js uses chromium i guess this is a something thats happens in chromium. How can I work around this?
This is what happens in my app:
When you enter a number containing a comma char. The comma char is moved to the right and when the input box loses focus, the comma is removed (Probably since the comma char isn't allowed in type=number)
When you get the value of an <input type=number> but it isn't valid, then a blank string is returned. You could check this by doing this:
$("input[type=number]").keyup(function(e){
var key = e.which ? e.which : event.keyCode;
if(key == 110 || key == 188){
e.preventDefault();
var value = $(this).val();
console.log(value === "");
$(this).val(value.replace(",","."));
}
});
It will print true every time. Therefore, you need to
Since, on the keyup event, the input has already changed, you must change it to a keydown or keypress event.
Change value.replace(",", ".") to value + "." (since there will be no ",").
Actually, you need to insert it where the cursor is. I'll update that when I have time.
Finished code:
$("input[type=number]").keydown(function (e) {
var key = e.which ? e.which : event.keyCode;
if (key == 110 || key == 188) {
e.preventDefault();
var value = $(this).val();
console.log(value);
$(this).val(value + ".");
}
});
A better idea might be to make it <input type=text> and validate manually if you really need this feature.
It's probably better not to mess with the actual data in the input field but reformat internally before reading, accessing the value through a getter like this:
var getInputNumber = function(inputid) {
return $(inputid).val().replace(",", ".");
};
$("input").keydown(function (e) {
var key = e.which ? e.which : event.keyCode;
if (key == 110 || key == 188) {
var value = $(this).val();
if (!isNaN(value)) {
e.preventDefault();
$(this).val(value + ".");
}
}
});

How to find out user pressed "enter" in text input?

I'm trying to add text input's element to my array when user pressed enter key. but I don't know how to do that. I tried this if statements but they didn't work:
var val = $("#txbxfeeds").val();
if (val[val.length-1] == "\r") {
alert("HI");
}
if (val[val.length-1] == "\n") {
alert("HI");
}
How can I do this?
I can suggest the following:
var vals = [];
$("#txbxfeeds").on("keypress", function(e) {
if (e.which == 13) {
vals.push(this.value);
}
});
DEMO: http://jsfiddle.net/Q4CUf/
$("#txbxfeeds").on('keyup', function(e) {
//13 is the code for enter button
var val = $(this).val(); // or this.value
if(e.which == 13) {
alert( val );
}
});
Working sample
Read more about jQuery event.which

Categories