How to identify what keyboard language is with jquery - javascript

is there any way to identify the keyboard language?
i have a simple textbox. that i want to check keyboard language. when the user click on textbox if the keyboard language was Contrary to Persian the user can't type anything and show the error:" change your keyboard language to persian" and when the keyboard language changed user can type.

I have used two different approaches for detecting English and Persian characters in my solution:
document.getElementById('a').addEventListener('keypress',function(e){
if (isEnglish(e.charCode))
console.log('English');
else if(isPersian(e.key))
console.log('Persian');
else
console.log('Others')
});
function isEnglish(charCode){
return (charCode >= 97 && charCode <= 122)
|| (charCode>=65 && charCode<=90);
}
function isPersian(key){
var p = /^[\u0600-\u06FF\s]+$/;
return p.test(key) && key!=' ';
}
<input id="a" type="text"/>

I don't think that's possible - anyway it's probably not what you want (Caps Lock, for example, will still output English)
I'd recommend placing a keypress event listener on your textarea and checking each letter against a "Persian only" regex
like this (untested):
document.getElementById('a').addEventListener('keypress',function(e){
if (e.charCode > 160)
console.log('persian');
else
console.log('english');
});
<input type="text" id="a"/>

If you want to match ZERO WIDTH SPACE you should add this too:
\u200B
So
var p = /^[\u0600-\u06FF\u200B\s]+$/;
for more characters like ” | « | » | ?| ; | : | ... see Regex Persian Language

using jquery :
$("#selector").keyup(function (event) {
var code = event.key.charCodeAt(0);
if (isEnglish(code)) {
alert("you typed in english");
return;
}
else {
alert("please type in english");
}
});
function isEnglish(charCode) {
return (charCode >= 97 && charCode <= 122)
|| (charCode >= 65 && charCode <= 90);
}

This:
function only_persian(str){
var p = /^[\u0600-\u06FF\s]+$/;
if (!p.test(str)) {
alert("not format");
}
}
or you can use this: http://imanmh.github.io/persianRex/

Related

Disable text when input number uses placeholder

How to disable text when using placeholder?
jsfiddle
<input type="number" placeholder="Min.">
EDIT
The input number should allow the user to enter only numbers.
This stops the user from inputting any character which is not a number, while still allowing them to use non-printable keys (ctrl, alt, backspace, enter, etc.)
This first part is from this answer to a different question
The second part basically checks every time the user presses a key, to see if that key was...
Printable, and
Not a number
If both of these conditions are met, prevent the character from being entered.
// https://stackoverflow.com/a/12467610/4639281
function printable(keycode) {
var valid =
(keycode > 47 && keycode < 58) || // number keys
keycode == 32 || keycode == 13 || // spacebar & return key(s) (if you want to allow carriage returns)
(keycode > 64 && keycode < 91) || // letter keys
(keycode > 95 && keycode < 112) || // numpad keys
(keycode > 185 && keycode < 193) || // ;=,-./` (in order)
(keycode > 218 && keycode < 223); // [\]' (in order)
return !!valid;
}
// This part is me
document.getElementById('min').onkeydown = function(e) {
var char = String.fromCharCode(e.keyCode);
if(printable(e.keyCode) & isNaN(char)) {
e.preventDefault();
}
}
<input type="text" placeholder="Min." id="min">
The jquery numeric plugin did the trick. Thank you all for the help. I had to write more text because the answer should be 30 characters minimum.
$(document).ready(function(){
$(".numeric").numeric();
});

Backspace (deleting characters) not working properly in Firefox due to Javascript

I am writing some Javascript/Jquery for a co-worker that is supposed to edit text in a textfield as the user is typing. The purpose of the code is to add formatting to a string of characters (in particular, formatting strings of twelve characters into a valid formatted mac address), however on Firefox I am unable to use the backspace to delete characters once they have been entered into the textfield.
Here is the code that does the formatting:
$(document).ready(function () {
var length = 0;
$("#mac_input").focusin(function (evt) {
$(this).keypress(function () {
content = $(this).val();
content_pre_format = content.replace(/\:/g, '');
content_formatted = content_pre_format.replace(/\n/g, '');
var text_input = $('#mac_input');
if (content_formatted.length % 12 == 0 && length != 0) {
text_input.val(text_input.val() + "\n");
}
length = content_formatted.length % 12;
if (length % 2 == 0 && length != 0) {
if (text_input.val().charAt(text_input.val().length - 1) == ':') {
} else {
text_input.val(text_input.val() + ':');
}
}
});
});
});
Edit: I figured out more about the bug. When I start typing, lets say "abc", right when I type the "c" the script edits the field to show "ab:c". I can backspace the "c" and the ":" but no more. At this point the text field shows "ab", however if I use ctrl-a to select all, the text field changes to "ab:"
here's a more robust solution (current solution will break if a user starts deleting anywhere except the end of the stirng):
$(document).ready(function() {
$("#mac_input").keydown(function (event) {
if (!((event.which > 47 && event.which < 71) || (event.which > 95 && event.which < 106))) {
event.preventDefault();
}
});
$("#mac_input").keyup(function () {
var content=$(this).val();
content = content.replace(/\:/g, '');
content = content.replace(/\n/g, '');
content = content.replace(/(\w{12}(?!$))/g, '$1\n').replace(/(\w{2}(?!\n)(?!$))/g, '$1:')
$(this).val(content);
});
});
it ensures the string is always parsed as a collection of MAC addresses
to explain, it uses to regular expressions,
([abcdef0123456789]{12}(?!$)) matches any sequence of twelve characters that can conform a MAC address and aren't at the end of the string (that's what the (?!$)) lookahead does), and replaces it with the matched string and an appended newline, then it matches any sequence of 2 MAC address characters (([abcdef0123456789]{2}) that aren't immediately followed by a new line or the end of the string ((?!\n)(?!$)).
Just check this: if(event.key == "Backspace") {return;} at the beginning of your keypress handler, and you should be fine.
NB: You have to add the event argument to your keypress handler function.

Have an irremovable question mark at the end of html input

I've looked around for ages trying to figure out this, hope you can help me.
Basically I have a feature on my site where the user can post a question. Essentially I want a permanent question mark at the end of what they're typing. The question mark is already added in the back end so this is strictly a visual problem.
The question mark moves up when they type.
I can't attach a photo but you can imaging :
The user typing here and after the type line there's a trailing question mark (type line-->)|?
Thanks in advance!!
You could do this :
$('#a').keyup(function(){
var v = this.value.replace(/\?/g, '') + '?';
if (this.value != v) this.value = v;
});
Demonstration
But users don't really like when the content of the input changes of its own. I'd avoid this if possible.
This second version puts a space before the ? :
$('#a').keyup(function(){
var v = this.value.replace(/ ?\?/g, '') + ' ?';
if (this.value != v) this.value = v;
});
Demonstration
Use a little javascript.
Attach an event onto the onkeyup event of the tickbox, and whenever it fires, check to see if the contents end with a question mark. If it doesn't, then add it!
Personally though, it would annoy me, as a user-I'd prefer to only see the question mark once I'be submitted.
I would perhaps instead recommend that you do a check on the server to see if the question contains a question mark (or multiple) at the end, then replace/add the single question mark.
As stated already, it's not really friendly to force a certain input - do the proper checks yourself and take the burden off the user.
If the goal is simply visual reinforcement, then it might be easiest to put a text or graphical question mark outside the text input, possibly in an interesting color, like bold green.
You don't really want to be trying to manipulate the input as the user is typing; you will likely always run into edge cases where the content gets mangled. If it's purely for presentational purposes, just add a ? character just after the input; if you surround it with something like a span, you can target it with CSS to adjust its size or font weight to make it more obvious:
.jumbo
{
font-size: 2em;
}
<input /><span class="jumbo">?</span>
An alternate solution (but overkill if you aren't already using it) is to use an icon font like FontAwesome and add, say, the question-mark icon: http://fortawesome.github.io/Font-Awesome/icon/question/
<input /><i class="icon-question icon-large"></i>
you can put the editable text inside a contenteditable span followed by another span that has the non editable question mark.
http://jsfiddle.net/Paawn/1/
<div class="box">
<span contenteditable="true">This is content i can edit</span>
<span class="question-mark">?</span>
</div>
Here's a pretty decent solution built off of ideas above and elsewhere on stack overflow. Using jQuery
Just add the following snippet and then add the class questionableInput to your input
<input id="yourInput" type="text" name="theInput" class="questionableInput"/>
(function($) {
$.fn.getCursorPosition = function() {
var input = this.get(0);
if (!input) return; // No (input) element found
if ('selectionStart' in input) {
// Standard-compliant browsers
return input.selectionStart;
}
}
$.fn.setCursorPosition = function(pos) {
var input = this.get(0);
if (!input) return; // No (input) element found
if ('selectionStart' in input) {
// Standard-compliant browsers
input.selectionStart = pos;
input.selectionEnd = pos;
}
}
$(".questionableInput").keyup(function(e) {
if (e.keyCode == 37 || e.keyCode == 38 || e.keyCode == 39 || e.keyCode == 40 || e.keyCode == 13
|| e.keyCode == 8 || e.keyCode == 17 || e.keyCode == 16 || e.keyCode == 36 || e.keyCode == 63
|| e.keyCode == 35 || e.ctrlKey) {
return;
}
var positionBeforeMessingWithIt = $(this).getCursorPosition();
if (this.value.slice(-1)!='?') this.value += '?';
if (this.value.slice(-2)=="??") this.value = this.value.substring(0, this.value.length - 1);
$(this).setCursorPosition(positionBeforeMessingWithIt);
});
})(jQuery);
http://jsfiddle.net/YpEgN/2/

JavaScript to accept only numbers between 0 to 255 range

My Requirement is to validate the ip ranges, I need to create a JavaScript function to accept only numeric and it must allow only between the range 0 to 255. If anything is entered beyond that it must alert a message.
I am currently using this below function
<script language="JavaScript">
function allownums(a)
{
if(a <48 ||a > 57)
alert("invalid")
else
alert("vaild")
}
</script>
<input type='text' id='numonly' onkeypress='allownums(event.keycode)'>
I am new to JavaScript, Need some experts suggestion to fix my requirement. Please suggest me
Thanks
Sudhir
Currently you have the test
(a < 48) || (a > 57)
for invalid values. So I would change those:
(a < 0 ) || (a > 255)
You may also need to consider what you'll do with non-integral input like 2.3 - either round it or treat it as invalid.
At present, as Kelvin Mackay points out, you are performing the validation on the keypress event rather than the input value, so change the onkeypress to allownums(this.value).
I would advise changing the alert to a warning in a div, and using the validation to enable/disable a submit button, as popups are quite annoying in just about every circumstance.
To clear the input when an invalid entry is made (as requested in a comment) would make it rather annoying for the user; as soon as a key is pressed to add a digit and make the input invalid, the whole input is cleared. The code, however, would be:
if(!validnum(this.value))
this.value="";
in the input tag, thus:
<input type='text' id='numonly'
onkeyup='if(!validnum(this.value)) this.value="";'>
with the function changed to:
function validnum(a) {
if(a < 0 || a > 255)
return false;
else
return true;
}
or more succinctly:
function validnum(a) {
return ((a >= 0) && (a <= 255));
}
Edit: To alert and clear the box, if you must:
function validOrPunchTheUser(inputElement) {
if(!validnum(inputElement.value)) {
window.alert('badness'); // punch the user
inputElement.value = ""; // take away their things
}
}
<input type='text' id='numonly'
onkeyup='validOrPunchTheUser(this)'>
However, reading other answers, apparently you are looking to validate an octet (e.g. in an IP address). If so, please state that in the question, as it passed me by today. For an octet:
function validateIPKeyPress(event) {
var key = event.keyCode;
var currentvalue = event.target.value;
if(key < 96 || key > 105)
{
event.preventDefault();
window.alert('pain');
return false;
}
else if(currentvalue.length > 2 ||
(currentvalue.length == 2 &&
key > 101)) {
window.alert('of death');
event.preventDefault();
event.target.value = event.target.value.substring(0,2);
}
else
return true;
}
With the input tag:
<input type='text' id='octet'
onkeydown='validateIPKeyPress(event)'>
Except please don't use alerts. If you take out the alert lines, it will silently prevent invalid inputs. Note the change to use onkeydown now, so that we can catch invalid key presses and prevent the value changing at all. If you must clear the input, then do if(!validateIPKeyPress(event)) this.value = "";.
I would rather go instantly for validation of whole ip address. Allowing input both numbers and dots, parsing them thru REGEX pattern.
Pattern usage example you could fetch here:
http://www.darian-brown.com/validate-ip-addresses-javascript-and-php-example/
The code itself would look something like:
<input type='text' id='numonly' value="" onkeypress='allowIp(event)' onkeyup='javascript:checkIp()'>
function allowIp(e){
if((e.keyCode < 48 || e.keyCode > 57) && e.keyCode != 46) // both nubmer range and period allowed, otherwise prevent.
{
e.preventDefault();
}
}
function checkIp()
{
var ip = $("#numonly").val();
/* The regular expression pattern */
var pattern = new RegExp("^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.)(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.)(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.)([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$");
/* use javascript's test() function to execute the regular expression and then store the result - which is either true or false */
var bValidIP = pattern.test(ip);
if(bValidIP){
// IP has ok pattern
$("#numonly").css("background", "green");
}
else {
$("#numonly").css("background", "red");
}
}
You could check it here on fiddle
http://jsfiddle.net/Indias/P3Uwg/
Single Integer
You can use the following solution to check if the user input for a single integer is between 0 - 255:
document.getElementById('example').addEventListener('input', event => {
const input = event.target.value;
console.log(/^\d+$/.test(input) && input > -1 && input < 256);
});
<input id="example" type="text" placeholder="Enter single integer" />
IP Address
Alternatively, you can use the code below to verify that each section of an IP address is between 0 - 255:
document.getElementById('example').addEventListener('input', event => {
const input = event.target.value;
console.log(input === new Uint8ClampedArray(input.split('.')).join('.'));
});
<input id="example" type="text" placeholder="Enter IP address" />
You need to validate the current value of the input, rather than the last key that was pressed:
<input type='text' id='numonly' onkeypress='allownums(this.value)'>
Your function then just needs to be modified to: if(a < 0 || a > 255)
A function like this should do it:
function allownums(value){
var num = parseInt(value,10);
if(num <0 || num>255)
alert('invalid')
}
Then have your html look like:
<input type='text' id='numonly' onblur='allownums(this.value)'>
Live example: http://jsfiddle.net/USL3E/
Update
I've set up a fiddle that does some basic IP-formatting and checks weather or not all input is in range (0 - 255) etc... feel free to use it, improve it, study it... I've also updated the code snippet here to match the fiddle
There are several things you're not taking into account. First and foremost is that not all browsers have a keycode property set on the event objects. You're better off passing the entire event object to the function, and deal with X-browser issues there. Secondly, you're checking key after key, but at no point are you checking the actual value that your input field is getting. There are a few more things, like the use of the onkeypress html attribute (which I don't really like to see used), and the undefined return value, but that would take us a little too far... here's what I suggest - HTML:
<input type='text' id='numonly' onkeypress='allowNums(event)'>
JS:
function allowNums(e)
{
var key = e.keycode || e.which;//X-browser
var allow = '.0123456789';//string the allowed chars:
var matches,element = e.target || e.srcElement;
if (String.fromCharCode(key).length === 0)
{
return e;
}
if (allow.indexOf(String.fromCharCode(key)) === 0)
{//dot
element.value = element.value.replace(/[0-9]+$/,function(group)
{
return ('000' + group).substr(-3);
});
return e;
}
if (allow.indexOf(String.fromCharCode(key)) > -1)
{
matches = (element.value.replace(/\./g) + String.fromCharCode(key)).match(/[0-9]{1,3}/g);
if (+(matches[matches.length -1]) <= 255)
{
element.value = matches.join('.');
}
}
e.returnValue = false;
e.cancelBubble = true;
if (e.preventDefault)
{
e.preventDefault();
e.stopPropagation();
}
}​
Now this code still needs a lot of work, this is just to get you going, and hopefully encourage you to look into the event object, how JS event handlers work and all the rest. BTW, since you're new to JS, this site is worth a bookmark
function fun_key()
{
var key=event.keyCode;
if(key>=48 && key<=57)
{
return true;
}
else
{
return false;
alert("please enter only number");
}
}
and you can call this function on keypress event like:
<asp:textbox id="txtphonenumber" runat="server" onkeypress="return fun_key()"> </asp"textbox>
I've seen many answers that have overlooked two important factors that may fail to validate range number on keypress:
When the value in input textbox is NOT SELECTED, the real outcome should be (input.value * 10) + parseInt(e.key) and not simply input.value + parseInt(e.key). It should be * 10 because you add one more digit at the back during keypress, e.g. 10 becomes 109.
When the value in input textbox IS SELECTED, you can simply check if Number.isInteger(parseInt(e.key)) because when 255 is selected, pressing 9 will not turn into 2559 but 9 instead.
So first of all, write a simple function that check if the input value is selected by the user:
function isTextSelected (input) {
if (!input instanceof HTMLInputElement) {
throw new Error("Invalid argument type: 'input'. Object type must be HTMLInputElement.");
};
return document.getSelection().toString() != "" && input === document.activeElement;
}
Next, this will be your on keypress event handler that takes into consideration of the above two factors:
$("input[type='number']").on("keypress", function (e) {
if (!Number.isInteger(parseInt(e.key)) || (($(this).val() * 10) + parseInt(e.key) > 255
&& !isTextSelected($(this)[0]))) {
e.preventDefault();
};
});
Take note of this condition within another brackets, it is one whole condition by itself:
(($(this).val() * 10) + parseInt(e.key) > 255 && !isTextSelected($(this)[0]))
For the < 0 condition, you don't even need it here because the negative sign (-) will be automatically prevented as the sign itself is not an integer.
KNOWN ISSUE: The above solution, however, does not solve the situation when the user move the cursor to the start position of 29 and press 1, which will become 129. This is because 29 * 10 = 290, which already exceed 255, preventing user from entering 129, which is valid. The start position is particularly hard to track when the input type="number". But it should be enough to resolve the normal way of input for an integer range field. Any other better solutions are welcome.

Can I conditionally change the character entered into an input on keypress?

Is it possible to change the character which has been entered on keypress, without doing it manually?
For example, if I want to force uppercase letters based on some condition, it'd be nice to do the following:
function onKeypressHandler(e)
{
if ( condition )
{
e.which -= 32;
}
}
But of course that doesn't work.
NOTE: This is not an across the board uppercasing, but only specific characters.
Maybe I want to say if ( e.which >= 97 && e.which <= 102 ) or if ( Wind.Direction == 'South' ) or whatever - the condition itself is not important, but the uppercasing must only apply to the current character not the entire input.
I can do it by manually appending the changed character, but this is an ugly and messy way of doing it, and probably slower than it could be.
function onKeypressHandler(e)
{
if ( condition )
{
$j(this).val( $j(this).val() + String.fromCharCode( e.which - 32 ) );
return false;
}
}
A specific flaw with this method - if selecting all input text and entering a key, if it drops into this then it doesn't remove existing content, but simply appends to the content the user wanted removed. (Would need to investigating detecting any selected text to solve that, which makes this one even uglier.)
Can anyone provide a better solution?
The following will do the job. It's based on an answer I wrote to another question. Customize the transformTypedChar function to suit your needs; my example capitalizes only the letters a-g.
If you need this on a textarea rather than an <input type="text"> then be aware that there are issues in IE <= 8 with line breaks that the following code doesn't handle for the sake of brevity. You can find the cross browser function for obtaining the selection within a textarea here: Is there an Internet Explorer approved substitute for selectionStart and selectionEnd?
function transformTypedChar(charStr) {
return /[a-g]/.test(charStr) ? charStr.toUpperCase() : charStr;
}
document.getElementById("your_input_id").onkeypress = function(evt) {
var val = this.value;
evt = evt || window.event;
// Ensure we only handle printable keys, excluding enter and space
var charCode = typeof evt.which == "number" ? evt.which : evt.keyCode;
if (charCode && charCode > 32) {
var keyChar = String.fromCharCode(charCode);
// Transform typed character
var mappedChar = transformTypedChar(keyChar);
var start, end;
if (typeof this.selectionStart == "number" && typeof this.selectionEnd == "number") {
// Non-IE browsers and IE 9
start = this.selectionStart;
end = this.selectionEnd;
this.value = val.slice(0, start) + mappedChar + val.slice(end);
// Move the caret
this.selectionStart = this.selectionEnd = start + 1;
} else if (document.selection && document.selection.createRange) {
// For IE up to version 8
var selectionRange = document.selection.createRange();
var textInputRange = this.createTextRange();
var precedingRange = this.createTextRange();
var bookmark = selectionRange.getBookmark();
textInputRange.moveToBookmark(bookmark);
precedingRange.setEndPoint("EndToStart", textInputRange);
start = precedingRange.text.length;
end = start + selectionRange.text.length;
this.value = val.slice(0, start) + mappedChar + val.slice(end);
start++;
// Move the caret
textInputRange = this.createTextRange();
textInputRange.collapse(true);
textInputRange.move("character", start - (this.value.slice(0, start).split("\r\n").length - 1));
textInputRange.select();
}
return false;
}
};
How about preventing default action and then triggering the keypress? Something like,
function onKeypressHandler(e)
{
if ( condition )
{
e.preventDefault();
// create new event object (you may clone current e)
var ne = new jQuery.Event("keypress");
ne.which = e.which - 32;
$(e.target).trigger(ne); // you may have to invoke with setTimeout
}
}
You've got to see this.. I was pretty happy with myself after getting it to work..
You obviously would want to include sufficient criteria to avoid going into a loop here.
The code below returns false when condition evaluates to true, but it fires the same event with a different charCode which will not return false.
document.getElementById("input1").onkeypress = Handler;
function Handler(e)
{
e = e || window.event;
if ( e.charCode == 97 )
{
var evt = document.createEvent("KeyboardEvent");
evt.initKeyEvent("keypress",true, true, window, false, false,false, false, 0, e.charCode -32);
this.dispatchEvent(evt);
return false;
}
return true;
}
you could use fireEvent in IE...
I used
http://help.dottoro.com/ljrinokx.php
and
https://developer.mozilla.org/en/DOM/event.initKeyEvent for reference
Not really sure what you want but will this work?
$('#my_element').keyup(function(){ $(this).val().toUpperCase(); });
or use a sub string to get the last character pressed and do toUpperCase() on that?
(psst... you can use keydown or keypress too).
Can you use css?
<input type="text" style="text-transform: uppercase;" />
Peter,
You might find some inspiration here:
http://www.maconstateit.net/tutorials/JSDHTML/JSDHTML15/jsdhtml15-05.htm
basically walks around the various ways to look at the keypress events and functions around that 'area'.

Categories