changing character code with js and show the new character instead - javascript

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).

Related

Real time input text filtration which allows only numbers

Hello I'm trying to make real time input type="text" filter which allows only numbers and dot, using javascript.
I wrote
Javascript:
<script>
function thirdTaskFunction(evnt) {
evnt = evnt || window.event;
var charCode = evnt.which ? evnt.which : evnt.keyCode;
return /\d/.test(String.fromCharCode(charCode));
}
function thirdTaskFunction(evt) {
var charCode = (evt.which) ? evt.which : evt.keyCode;
if(charCode > 31 && (charCode < 48 || charCode > 57)) {
return false;
}
return true;
}
function thirdTaskFunction() {
var thirdInput = document.getElementById("thirdTaskInputText");
thirdInput = thirdInput.onchange = thirdTaskFuncion;
var valid = /^\-?\d+\.\d*$|^\-?[\d]*$/;
var number = /\-\d+\.\d*|\-[\d]*|[\d]+\.[\d]*|[\d]+/;
if(!valid.test(this.value)) {
var compare = this.value.match(number);
this.value = compare ? compare[0] : '';
}
}
</script>
HTML:
<div id="thirdTaskDIV">
<input id="thirdTaskInputText" type="text" placeholder="Type a number" autofocus onkeypressed="return thirdTaskFunction(event);">
</div>
I was trying many ways, every thirdTaskFunction() method wasn't work, I was tested solution on w3schools so maybe this is reason? But I think that I dont remember about something that make it works. And I know is very similar to "HTML text input allow only numeric input" but it didnt works.. So I hope somebody show me whats pappyn here.
One way to allow only numbers in an input field is using a keypress event listener. So you'll want to select the input field and give it an event listener, like this:
const inputField = document.querySelector("/*input field id here*/");
inputField.addEventListener("keypress", function(e){
if(e.keyCode > 48 && e.keyCode < 57){
e.preventDefault();
}
}
This function checks if the key that's pressed matches a number key, and if it doesn't, prevents the default action which in this case is printing the character to the input field.
If you have any questions, I'll do my best to answer them!
P.S. The keyCode numbers used are estimates based on memory, to get the key codes simply do a quick search on google for "ASCII key codes".
The event code (NOT keyCode since the keyCode property is deprecated) for the dot is Period and the event code for the numbers 0 to 9 comes in the form Digit0, Digit1 and so on.
Just use the keydown event listener to retrieve the event code and then use the includes() method to check if the current key has a code that includes "Digit" or "Period" and restrict input of that character if it doesn't include either of those two by using preventDefault() like this:
const input = document.getElementById('thirdTaskInputText');
function checkKey(e) {
if(e.code.includes("Digit") || e.code.includes("Period")) {
console.log("valid input");
} else {
e.preventDefault();
console.log("not a number!");
}
}
input.addEventListener('keydown', checkKey)
<input id="thirdTaskInputText" type="text" placeholder="Type a number">
Without the console logs, you can further simplify the above code to a single if statement using the bang operator ! like this:
const input = document.getElementById('thirdTaskInputText');
function checkKey(e) {
if(!(e.code.includes("Digit") || e.code.includes("Period"))) e.preventDefault();
}
input.addEventListener('keydown', checkKey)
<input id="thirdTaskInputText" type="text" placeholder="Type a number">

Detect Tab Key event on textbox on focus

I have a autocomplete textbox in a form and I want to detect whether user has focussed on the textbox from navigating through tab key press.I mean tabindex has been set up on different form fields and user can navigate fields by pressing tabs.Now I want to perform some action when user directly mouse click/foxus on the textbox and some other action when user has focussed on the textbox through tab.
Below is the code I was trying.But no matter everytime code is 0.
$('#tbprofession').on('focus', function (e) {
var code = (e.keyCode ? e.keyCode : e.which);
if (code == 9) {
alert('Tabbed');
}
else
{
alert('Not tabbed');
}
});
This code does not work.
Note:Before marking duplicate it will be good if you understand the question correctly.Else I can make it more clear with more elaborated description.
Anyone can show me some light?
You can try something like that :
$(document).on("keyup", function(e) {
if ($('#tbprofession').is(":focus")) {
var code = (e.keyCode ? e.keyCode : e.which);
if (code == 9) {
alert('I was tabbed!');
} else {
alert('not tabbed');
}
}
});
fiddle : https://jsfiddle.net/xc847mrp/
You can use keyup event instead:
$('#tbprofession').on('keyup', function(e) {
var code = (e.keyCode ? e.keyCode : e.which);
if (code == 9) {
console.log('I was tabbed!', code);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input autofocus>
<input id='tbprofession'>
You could have an array of key events triggered anytime a user presses a key while on your page. Although this makes you think of a keylogger.
Or just keep the last key.
Or a boolean saying if the last key pressed was a TAB or not.
And on focus you can look at that variable.

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 + ".");
}
}
});

Restrict characters in input field

Is there a way to block users from writing specific characters in input fields? I tried the code below, but when a user enters disallowed characters, they appear for a brief period before disappearing. I want the input to remain unchanged when invalid characters are written.
I want to use onchange because other restriction methods do not seem to work on mobile devices. The problem I want to solve is that characters appear briefly before being removed.
function checkInput(ob) {
const invalidChars = /[^0-9]/gi;
if(invalidChars.test(ob.value)) {
ob.value = ob.value.replace(invalidChars, "");
}
};
<input class="input" maxlength="1" onChange="checkInput(this)" onKeyup="checkInput(this)" type="text" autocomplete="off" />
you can use try this,
$('.input').keyup(function () {
if (!this.value.match(/[0-9]/)) {
this.value = this.value.replace(/[^0-9]/g, '');
}
});
SEE THIS FIDDLE DEMO
Updated :
You can try this Code,
$(document).ready(function() {
$(".input").keydown(function (e) {
// Allow: backspace, delete, tab, escape and enter
if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110]) !== -1 ||
// Allow: Ctrl+A
(e.keyCode == 65 && e.ctrlKey === true) ||
// Allow: home, end, left, right
(e.keyCode >= 35 && e.keyCode <= 39)) {
// let it happen, don't do anything
return;
}
// Ensure that it is a number and stop the keypress
if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
e.preventDefault();
}
});
});
SOURCE
SEE UPDATED FIDDLE DEMO
UPDATED FOR ANDROID:
<EditText
android:id="#+id/editText1"
android:inputType="number"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textView1"
android:layout_marginTop="58dp"
android:layout_toRightOf="#+id/textView1"
android:maxLength="1" >
</EditText>
I think it may help you... using android:inputType="number" you can do that.
A combination of keypress and paste events does a trick:
var text = document.getElementById('text');
text.onkeypress = text.onpaste = checkInput;
function checkInput(e) {
var e = e || event;
var char = e.type == 'keypress'
? String.fromCharCode(e.keyCode || e.which)
: (e.clipboardData || window.clipboardData).getData('Text');
if (/[^\d]/gi.test(char)) {
return false;
}
}
<input class="input" maxlength="10" id="text" type="text" autocomplete="off" />
This code prevents from typing or pasting anything but a number. Also no blinking and invalid characters don't show up.
Works in IE7+.
Demo: http://jsfiddle.net/VgtTc/3/
All answers given so far suffer from at least one of the following accessibility issues:
They validate key codes, which does not work with non-QWERTY keyboard layouts.
They do not cover all input methods; especially drag&drop is often forgotten.
They alter the value, which resets the position of the caret.
They use the pattern attribute, but this does not provide feedback until the form is submitted.
Wouldn't it be a much better idea to actually validate the input before it's inserted?
The beforeinput event fires before the input's value is changed. The event has a data property which describes the content that the user wants to add to the input field. In the event handler, you simply check the data attribute, and stop the event chain if it contains disallowed characters.
We end up with the following very simple, very short code.
const input = document.getElementById("input");
const regex = new RegExp("^[0-9]*$");
input.addEventListener("beforeinput", (event) => {
if (event.data != null && !regex.test(event.data))
event.preventDefault();
});
<label for="input">Enter some digits:</label>
<input id="input" />
Some closing notes:
Accessibility: Provide a clear explanation of what input format is expected from the user. For example, you can use the title attribute of the input to show a tooltip explaining the expected format.
Security: This is client-side validation, and does not guarantee that the pattern is enforced when the form is sent to a server. For that, you'll need server-side validation.
Here's a little hack you could try: DEMO
What it does is that it colors every input text white and then changes it back to black if it suits your requirements. If you could live with the bit of lag that occurs when you enter a valid character.
function checkInput(ob) {
var invalidChars = /[^0-9]/gi
if (invalidChars.test(ob.value)) {
ob.value = ob.value.replace(invalidChars, "");
}
else {
document.getElementById('yourinput').style.color = '#000';
}
};
function hideInput(ob) {
document.getElementById('yourinput').style.color = '#FFF';
};
html
<input id="yourinput" class="input" maxlength="1" onKeydown="hideInput(this)" onKeyup="checkInput(this)" type="text" autocomplete="off" />
css
input {color:#FFF;}
check this code,
$('.input').keypress(function(e) {
var a = [];
var k = e.which;
for (i = 48; i < 58; i++)
a.push(i);
if (!(a.indexOf(k)>=0))
e.preventDefault();
});
​
<input id="testInput"></input>
<script>
testInput.onchange = testInput.oninput = restrict;
function restrict() {
testInput.value = testInput.value.replace(/[^a-z]/g, "");
}
</script>
I came up with something slightly different. oninput instead of onkeyup/onkeydown, and onchange instead of onpaste.
I restrict invalid characters on both keypress and paste events like:
<input type="text" onkeydown="validateKey(event)" onpaste="validatePaste(this, event)">
And define functions to handle these events inside tab or a separate javascript file:
<script>
function validateKey(e) {
switch(e.keyCode) {
case 8,9,13,37,39:
break;
default:
var regex = /[a-z .'-]/gi;
var key = e.key;
if(!regex.test(key)) {
e.preventDefault();
return false;
}
break;
}
}
function validatePaste(el, e) {
var regex = /^[a-z .'-]+$/gi;
var key = e.clipboardData.getData('text')
if (!regex.test(key)) {
e.preventDefault();
return false;
}
}
</script>

Categories