how to accept only alphabetical pressed keys ( for "autocomplete" purpose ) - javascript

am wondering ... how to only accept alphabetical pressed keys from the keyboard .. i am using the jQuery .keypress method ... now i wanna know how to filter the passed key ...
i am trying to build a simple autocomplete plugin for jQuery ...i know a about jQuery UI, but i want to do it myself ...
thanks in advance :)

You can bind a function to the field that replaces anything that's not in the a-z range.
<input name="lorem" class="alphaonly" />
<script type="text/javascript">
$('.alphaonly').bind('keyup blur',function(){
$(this).val( $(this).val().replace(/[^a-z]/g,'') );
});
</script>
Source: Allow text box only for letters using jQuery?

In your callback, you can check the event's keyCode property. If you want to disallow the key being entered, simply return false. For example:
$('#element').keypress(function(e)
{
if(e.which < 65 || e.which > 90) //65=a, 90=z
return false;
});
Note that this won't really work very well. The user could still paste in other text, or use a mouse-based entry device, or any number of other things.
I've edited this based on Tim Down's comment and replaced keyCode with which, which is correct across keydown, keyup, and keypress events.

The following will prevent any character typed outside of a-z and A-Z from registering.
$("#your_input_id").keypress(function(e) {
if (!/[a-z]/i.test(String.fromCharCode(e.which))) {
return false;
}
});
This won't prevent pasted or dragged text appearing. The surest way to do that is the change event, which is only fired once the input has lost the focus:
$("#your_input_id").change(function(e) {
this.value = this.value.replace(/[^a-z]+/gi, "");
});

This worked for me, it only accepts letters no special characters or numbers
$("#your-input-here").keypress(function (e) { return validateAlphaKeyPress(e); });
function validateAlphaKeyPress(e) {
if (e.keyCode >= 97 && e.keyCode <= 122) {
return true;
}
return false;
}

Related

Altering the keypress event of certain keys in JavaScript

I am working on a project which shows the character code of each key that is pressed down inside a text box.
My problem is that when certain keys, namely: Shift, Backspace, Space are pressed down, their character codes appear like: 16, 8, 32.
I want these keys to retain their normal behavior when pressed. So that space causes a space in the text box, and backspace deletes the character, and so on...but the rest of the keys to continue outputting their character code.
How can I go about accomplishing this?
You can just check for the keys and handle accordingly. Here's a demo:
document.getElementById("test-textbox").addEventListener("keypress", function(event) {
var code = event.keyCode || event.which;
if(code === 16 || code === 8 || code === 32) //check if space, shift, or backspace
return; //if yes, allow
console.log(code); //if not, log value
event.preventDefault(); //prevent entry
});
<input type="text" id="test-textbox">
This will allow the shift, backspace, and space keys to be pressed, but all others will be logged.
I think this will work for you.
var elementID = document.getElementById('elementID');
elementID.onkeydown = function(event) {
var key = event.keyCode || event.charCode;
if( key == 32 || key == 8 )
event.preventDefault();
};
As long as you…
don’t call the preventDefault method on the event object, and
don’t return false from the event handler
…you should be fine.
In particular, the handler…
function showCharCode(event) {
// NOTE: Don’t call `event.preventDefault()` here.
document.querySelector('.char-code').textContent = event.charCode;
// NOTE: Don't return false here.
}
… will still propagate the event to the default textbox (or input, or contenteditable) element.

Get the keypress code without to care which symbol is clicked using JQuery

I see here is have few questions when is asking for how can get which key is clicked from keyboard. I tested is ok is working if is in English case.
If I change the language and the symbols on keyboard is changed then is not show anything.
So my question is how can I get the keypress code without to care which language is now used the user when is click the key 'G' or 'Г' or something else.
here is my simple jquery code
$(document).keypress(function(e) {
if (e.charCode == 103) {
alert('g');
} else if (e.charCode == 71) {
alert('G');
}
});
If is with english is working, when I change to Bulgarian then is not working. How can I make to working on every language?
Using the keypress event will give you the character typed, regardless of keyboard layout.
For character input, it is suggested you use keypress(), which will report the actual ASCII code for the character pressed. It automatically takes care of letter case, and ignores non-character presses. In either case, you can use fromCharCode() to convert to a string representation. E.g.
document.onkeypress = function(evt) {
evt = evt || window.event;
var charCode = evt.which || evt.keyCode;
var charTyped = String.fromCharCode(charCode);
alert("Character typed: " + charTyped);
};
I find the solution of my problem. Thanks of this article
$(document).on('keydown', function(e) {
if (e.ctrlKey) {
alert('Echo');
} else {
alert(e.which + ' ' + e.key);
}
});
What I'm changing. I change only the event. I replace 'keypress' with 'keydown' and now is the same code without to care which language is used.

keydown event - key pressed on different systems

I have a number input, which I want user to by unable to insert any non-digit characters. We have attempted this in a number of ways:
We started with removing all non-numeric characters on blur:
$(my_input).blur(function() {
$(this).val($(this).val().replace(/[^\d]/, '')
}
The problem with the code above is that number field's val function returns empty string if the input is invalid. We definitively want a number field as our website is to be used on mobiles.
The option which I would prefer is to use keydown event:
$(my_input).keydown(function(e) {
if (e.shiftKey === true ) {
if (e.which == 9) {
return true;
}
return false;
}
if (e.which > 57) {
return false;
}
if (e.which==32) {
return false;
}
return true;
});
The above works almost as a charm. The problems are:
numeric keyboard not included in a range - this can be however easily fixed and is not a subject of this question.
For unknown to me reasons js on iOS is using different key codes, hence this is not working on huge part of mobile phones, iPads etc.. This is a deal breaker.
So the question - is there any way to determine which key was actually pressed with an keydown event. I have seen number of similar questions, none of them however covered those iOS differences. I've noticed that event has a 'key' property, however I am not sure how reliable this property is.
EDIT: I fell on this post which might be a neat way to solve your problem:
JavaScript: Avoiding hardcoded keycodes
It would boil down to
var digitCodes = "0123456789".split('').map(function (x) { return x.charCodeAt(0); });
There might be a better way to do this but you could detect if the device is running iOS (c.f. Detect if device is iOS) and use the appropriate keycodes (c.f. http://notes.ericjiang.com/posts/333).
var digitCodes;
if (isiOS()) {
digitCodes = keycodes.ios;
}
else {
digitCodes = keycodes.default;
}
if (digitCodes.indexof(e.which) != -1) {
...
}
Something like that...
You can try it this way
sample text box
<input type="text" name="sample" id="sample" onkeyup="positiveNumericOnly(this);" />
JS Code
function positiveNumericOnly(ele)
{
tempVal = ele.value.replace(/[^\d]/g, "");
if(tempVal != ele.value)
ele.value = tempVal;
}

how to capture backspace key code in android browser - javascript?

I have a page made in pure HTML Javascript... I handle the keyup code and I need to get the key code, when key code == 8 (backspace) special task must be run... but if I open the page in android browser, chrome, or whatever... backspace doesn't return any key code...
I've made:
$( '.input-cell' ).bind( 'keyup', function( e ){
var keycode = e.keyCode ? e.keyCode : e.which;
alert( keycode );
if( keycode == 8 ) {
.....
}
});
The alert returns me all the keycodes but the backspace... is there any way to capture the backspace press event?
input change event
$('#myinput').bind('input', function(){
// code
});
backspace
$('#myinput').on('keypress', function() {
//code
}).on('keydown', function(e) {
if (e.keyCode==8) {
//code
}
});
Another solution can be check for the length of the characters before, and after, if it has less than one character than before, then clearly it was a backspace that fired, in my case I was using only one input with one character and needed to go back to the previous input after hitting a backspace, for my case I only got also 0 and 229 within the android keyboard, so I did this:
$('input').on('keydown', function (e) {
switch(e.keyCode){
case 229:
case 0:
if($(this).val() == '')
$(this).prev().focus();
break;
}
});
The same can be achieved by checking the characters, of course this will only be in the case of a backspace in the android keyboard device, is just a workaround, hope it helps.

Validating user input with JavaScript

I need to make it so a user can ONLY type a-z0-9 into my input box. How can I make it so the user simply cannot type other characters? If this isn't possible, how can I simply check the input with regex?
Thanks!
Another notable solution is this alphanumeric plugin for jquery:
http://itgroup.com.ph/alphanumeric/
Simple as $('#textField').alphanumeric();
If you use jQuery, there is a format plugin that does exactly what you need. Other than that, you can use onkeyup/onkeyup to call function which will validate input against regex pattern.
You can use the onKeyDown event. If you return false from your event handler, no key press event is fired and the key is "eaten".
Here are the docs from Sun: http://docs.sun.com/source/816-6408-10/handlers.htm#1120313
Here is a solution that's adapted a bit from this page:
window.onload = function () {
document.forms.myForm.myField.onkeypress = keyTest;
}
function keyTest(e)
{
var key = window.event ? e.keyCode : e.which;
var keychar = String.fromCharCode(key);
reg = /[a-z0-9]/i;
if (key != 8 && key != 9) return reg.test(keychar);
}
Make sure you also perform the validation on the server too (assuming there's a server part to this) in case some users have javascript turned off.

Categories

Resources