Jquery detect input focus - javascript

I am creating a conversion web app to teach myself Javascript. The user can input data with a number pad (basically a calculator without the operators). I also set up a function to detect keystrokes (1-9) which insert data just like the number pad. And also character 'c' which clears all data
My problem is that I also have a search field (which uses auto complete to enable the user to search for other conversions). I dont' want the user to search for something using the 'c' or number keys, and have it enter data into both the number pad, and search field.
My idea was to create a if statement to determine if the search field was active (focused), and if it was to change a variable (enabled) to false, thus disabling the keystroke detection.
The problem I am having is that the function holding the if statement with the focus attribute is not working.
If my rambling made no sense hopefully the code will clear things up.
Here is the if statement with the focus attribute
$(document).ready(function(){
if($(':focus').attr('#searchInput') == 'input')){
enabled === false;
}
});
Here is the code for key stroke detections (I omitted the redundant parts to save space
document.onkeydown = function(event){
var key = event.charCode || event.keyCode;
if(enabled === true){
if(key === 67){
clearInput(input); //Clears form input (input is my form ID)
}else if(key === 48){
writeInput(input, zero); //Zero is a var equaling 0
}
...
}else{
return false; //if enabled is false don't detect keystrokes
}
};
Any help would be greatly appreciated. If anything doesn't make sense I will be happy to explain (or edit the post.)

$(document).keyup(function(e){
if($('#searchInput').is(':focus')) {
return ; // search field is focused, ignore other part of function
}
var key = e.which;
// do your code here
});

Related

How can I access the result of this function on this other function?

So i have this text input field and I have the showKeyCode() function which gets the value from the text input and prints the keycode representation of the pressed key into the console.
function showKeyCode() {
$('#inputfield').keyup(function(e){
$(this).val(String.fromCharCode(e.keyCode));
console.log(e.keyCode);
});
}
const r4 = document.querySelector("#inputfield");
r4.addEventListener('input', showKeyCode2);
Now i want to get this value and use it at the function below.
$(document).keydown(function(e) {
if (e.which == [I WANT TO PUT THE RESULT FROM showKeyCode() HERE] ){
document.querySelector('#test').click()
console.log("Clicked");
}
});
Lets summarize what I'm trying to do here. If you are a gamer you must have used the keybinds for example : Press [M] to show minimap. Press [H] to show hud.
Here im trying to make the user customize the keybind by typing it into the text field. The showKeyCode() function gets the Character and converts it into a keycode which ill use in the second function.
I couldve typed the keycode directly into the script like this
if (e.which == 84 ){}
but i wanted the user to change it inside the game.
Technically "You can't" But there's a hacky and dirty workaround. Global variables.
//outside
let value = '';
function showKeyCode() {
$('#inputfield').keyup(function(e){
$(this).val(String.fromCharCode(e.keyCode));
value = e.keyCode;
});
}
$(document).keydown(function(e) {
if (e.which == [value] ){
document.querySelector('#test').click()
console.log("Clicked");
}
});
This should work if sowKeyCode was called before a keydown was made
Now, I DO NOT RECCOMMEND using global variables but sometimes its the only way on the approach, perhaps you can use a different method like putting this inside a class or using other libraries that are great with state tracking.

How to check for the multiple dots and stop to enter multiple dot using javascript?

I am having a input type text.
<input type="text" class="checkForDot" />
What i am trying to do is, when a user enters numbers into the box then find for the "." in the field, if it contains more then one ".", then prevent it to enter another "." in the text field.
my jquery code is:
$(".checkForDot").on("keyup", function (event) {
CheckForDot($(this).val());
});
function CheckForDot(value) {
if (value != null || value != '') {
var str = value.toString();
if (str.indexOf('.', str.indexOf('.') + 1) != -1) {
console.log("ok");
}
}
}
It is working fine, if two "." enters into the text box, but how to prevent to enter multiple "." in the text field?
If any other approach better than this please tell.
$(document).ready(function() {
var original='';
$('.checkForDot').on('input', function() {
if ($(this).val().replace(/[^.]/g, "").length > 1){
$(this).val(original);
}else{
original = $(this).val();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='text' class='checkForDot' />
Try to use this regex to find how many dots you got in string.
If you are looking to make a field that only allows for numbers, you should consider using an input of type="number" as they will only allow for valid number characters to by added to its value. In some cases, it might even bring a different visual keyboard to ease of filling, wich is better for accessibility and UX. The number input field will, by default allow for mutliple dots, wich is annoying and is a bit harder to prevent than in a text field so it's a case of figuring wether accessibility and your UX is more important than adding a few extra lines of Javascript.
A lot of people will tell you that it is bad practice to limit keyboard actions, and they are right. when you do a preventDefault() on everything but numbers and ".", you disable tabing through form fields, the browser alt menu, any ctrl shortcuts, anything that happens within the browser.
This solution is simple and will only allow one dot in the number field. It doesn't prevent from clicking back in the number and adding numbers before the ".". It doesn't prevent from executing browser keyboard shortcuts like refresh, copy and pasting, as long as the pasted value is a valid number. It will allow to add "." withing the body of the number.
The only behavior that can't be prevented is if the user press the dot key at the end of the input repeatedly, the dot will blink on and off. This happens because of the way the number field handles its value. Wen the user types a dot at the end of a number like "13.", javascript can only retreive "13" when looking at its value as long as no decimal number have been placed. If the user typed a dot again, the value of "13.." would not be a valid number and therefore javascript woudl retreive "". This ensure you eighter get a valid number or nothing at all. In my solution, if a value returns "" without the press of backspace, delete or cut, it gets rolled back to the last valid value, wich in my example was "13", obtained from the typed value "13.". Preventing this behavior seems practically impossible and isn't a deal breaker as you get ensured your field value is always a valid, single dot number.
let lastValidInputValue;
let selectedDot = false;
const onKeypress = (e) => {
if (e.key === "." && e.target.value.indexOf(".") !== -1 && !selectedDot) e.preventDefault();
selectedDot = false;
};
const onInput = (e) => {
if (e.target.value !== "") {
lastValidInputValue = e.target.value;
} else if (e.inputType.match(/delete/g)) {
lastValidInputValue = "";
} else {
e.target.value = lastValidInputValue;
}
};
const onSelect = (e) => {
selectedDot = (window.getSelection().toString().indexOf(".") > -1)? true : false;
}
<input type="number" id="myNumber" name="myNumber" step="any" onkeypress="onKeypress(event)" oninput="onInput(event)" onselect="onSelect(event)">
You can find very detailed comments and extra bits in this Codepen

Binding the "onselect" event to a function, that handles the maximum chars. inside an input text field

I am working on a function to limit the number of chars. a user is allowed to type inside an input text field.
This is it:
$.fn.restringLength = function (id, maxLen) {
$(id).keypress(function(e){
var kCode = e.keyCode ? e.keyCode : e.which,
len = $(id).val().length;
if (kCode != 8 && kCode != 46) {
if (len > maxLen) e.preventDefault();
}
});
}
The function binds the keypress event and gets the code of the pushed key.
If the char. limit is reached, it allows only the delete and backspace keys to be pushed.
What it needs to work great, is a way to bind the "onselect" event in order to have the following behavior:
when the user selects the whole text with the mouse, and types a letter or a number, the whole text gets deleted and that letter appears.
This is something that most of us do when we want to replace some text with another, and I'd like my function to enable this.
Any ideas how?
If i may add something,
Your solution use keypress event, so the event is triggered before the new value of input is computed. That's why you have to check for special key like backspace , enter ... theses do not just add a character to the string so they require special treatment.
For this kind of processing, it's more convinient to have the handler triggered after the string computation. In that way, you can access the input value and modify it if it's not correct.
Unfortunately jquery does not support this event but you can use it with vanilla javascript method.
$(id)[0] // get the vanilla js element
.oninput = function(e){
this.value = this.value.substr( 0 , 10 ) // this.value contain the string after the key press processing
}

Keyboard Number Line vs Keypad Numbers

I'm using Javascript, I need to get the keypad numbers. For what ever reason, my code treats them differently.
function getKey(keyStroke) {
var keyCode = (document.layers) ? keyStroke.which : event.keyCode;
var keyString = String.fromCharCode(keyCode).toLowerCase();
if (lop.charAt(cpos)==keyString) {
document.getElementById("pimachine_e").innerHTML=document.getElementById("pimachine_e").innerHTML+keyString;
cpos++;
} else {
lose();
}
}
The number line at the top of the keyboard acts like expected but the Numberpad is treated (when I click 1) as if I haven't clicked 1. What is it changing it to? How do I get these key presses correctly.
http://www.cambiaresearch.com/c4/702b8cd1-e5b0-42e6-83ac-25f0306e3e25/Javascript-Char-Codes-Key-Codes.aspx
That shows a list with all of the keys on a regular keyboard and the keycodes that are associated with it. As you can see, when pressing 'numpad 1', it should return '97' in this line:
var keyCode = (document.layers) ? keyStroke.which : event.keyCode;
Maybe you can put an alert after that line to check if the variable 'keyCode' has ben filled correctly?
If that doesn't help you along your way, please provide more code, cause I cannot recreate your situation locally because your function is referring to other pieces of code that are not provided. Also, I can't see how this function is being called and how the variable 'keyStroke' is filled.

onkeyup() event - possible to detect if key press was ignored because a field was at it's maxlength?

I have a form field for entering a user id. The user id is always 6 characters so the field is limited to a maxlength of 6 characters.
The field has an onkeyup() event to call a function that looks up the user id and fills in several other form fields if the user id is valid. Most people I know have used onblur() for something like this but I never liked how a user has to tab to or click on another field before the autofilling AJAX goes off.
The function right now will return w/o doing anything if the field length is < 6 characters or if the key that was pressed is a left or right cursor field.
There's one flaw left I haven't been able to think around. Since the field is limited to 6 characters, if 6 characters are already entered and another key is pressed, the value of the field will not change but the function will fire and validate the field (un-necessary validation/db-query).
Is there anyway to prevent the function from going off in this case? I'm thinking it's not possible but wanted to check. I had a thought if the field length was 6 I could check the last key pressed against the 6th character of the field, but if someone typed something like 'a' as the 6th character and then 'a' again, it wouldn't work. I guess that could eliminate all possibilities except for the one case though one case (not perfect but better).
(rails) <%= f.text_field :uid, :size => 10, :maxlength => 6, :class => 'validate_text', :onkeyup => uid_lookup (event)', :autocomplete => :off %>
<script type="text/javascript">
String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/g,"");
}
</script>
<script type="text/javascript">
uid_lookup = function(e){
var unicode=e.keyCode? e.keyCode : e.charCode;
if (unicode == 37 || unicode == 39) { // ignore a left or right arrow press
return
}
var uid= $('uid').value;
uid = uid.trim();
$('uid).value = uid; //uid's have no spaces, go ahead and remove if typed
if (uid.length != 6) {
return
}
// db lookup & form autofill
}
</script>
The solution is not to use onkeyup. The correct event to use is HTML5's oninput, which is supported by almost every major browser out there. The one browser lacking support is—of course—Internet Explorer 8, but we can emulate the event using IE's proprietary onpropertychange event which will fire whenever an input element's value property changes.
I'm not familiar with rails, but the best way to apply the event is using JavaScript so that you can gracefully degrade if oninput isn't supported:
var el = document.getElementById("myEl");
// Check support
if ("onpropertychange" in el && !("oninput" in el)) {
el.onpropertychange = function () {
if (event.propertyName == "value")
uuid_lookup.call(this, event);
}
}
else
el.oninput = uuid_lookup;
The other great thing about this event is that it only fires when the value changes - much like onchange but more real-time. This means you can do away with your key detection for left and right arrows in the uuid_lookup function.
Can you not use another variable to store the previous value of the field the last time the validation function was fired? Then you can simply return if uid.value = lastValue.
Not perfect, but it would save some processing.

Categories

Resources