I'm trying to remove a character as it's typed/keyed up to test whether it's a number or not, if it is a number, keep it, if not, remove it. It can be more than one digit. for example, I type in a "d", it should be deleted from the textbox. I then type a "1", where it should stay in the textbox. I then type a 4 and it also stays so the textbox now reads "14". Then I type "g", which should be deleted. Then I type a "5" and now the text box reads 145. This is what I have so far.
$("#txtTestNumbersOnlyRegex").keyup(function () {
$("#txtTestNumbersOnlyRegex").val(function (index, value) {
var keyPressed = value.substr(0, value.length - 1);
var regEx = new RegExp("/^5$/");
if(!regEx.test(keyPressed)) {
alert("true");
return value.substr(0, value.length - 1);
}
});
});
You might want to try this:
$("#txtTestNumbersOnlyRegex").keyup(function () {
var newValue = $(this).val().replace(/[^0-9]/g,'');
$(this).val(newValue);
});
You can try it here https://fiddle.jshell.net/aooh0gkz/
You can use regex to replace any non digits with empty space, although this will look a bit weird.
$('input').keyup(function() {
$(this).val($(this).val().replace(/\D/, ''));
});
Full snippet:
$('input').keydown(function() {
console.log($(this).val());
$(this).val($(this).val().replace(/\D/, ''));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text">
Or you could use input type="number" if you don't care about IE support.
You can intercept the values that are coming in and decide what to do, So it is better to have the keypress else your text gets replaced everytime and say if you are in middle of input val and you are editing caret will jump to the end in other cases
$("#txtTestNumbersOnlyRegex").keypress(function (event) {
var keyCode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;
if((keyCode>=65 && keyCode<=90) || (keyCode>=97 && keyCode<=122))
return false;
else return true;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type=text id = txtTestNumbersOnlyRegex />
Related
I'm coding a chat box. And the Characters that I enter, is not reflected as it is.
This is basically the code I'm using.
$(document).ready(function() {
$(".entry").keydown(function(event) {
console.log(String.fromCharCode(event.which));
});
});
And so when I type (lower-case) "a", console tab shows me "A".
special characters will not get reflected unless I create separate condition for it.
Could someone help me with a different function which does it all by itself, and returns a string as entered by the user. Or a different approach to this challenge all together. Thanks.
Actual code - chat.js
var str='';
$(document).ready(function() {
$(".entry").keydown(function(event) {
console.log(event.which);
if (event.which === 13 && event.shiftKey === false) {
console.log(str);
event.preventDefault();
} else {
var c = event.which;
str = str.concat(String.fromCharCode(c));
}
});
});
So basically the every character entered would get concated to the string. and Enter key would dump the text to console.
It's seems that trying to get the value of event.which in keydown event could lead you to a wrong ascii code (What you need to pass to String.fromCharCode).
See https://stackoverflow.com/a/10192144/3879872
I don't know if it fits your needs, but you could try:
$(document).ready(function(){
$(".entry").keypress(function(event) {
console.log(String.fromCharCode(event.which));
});
});
(Note the use of keypress instead of keydown)
EDIT: Added working Demo
var str = '';
$(document).ready(function() {
$(".entry").keypress(function(event) {
console.log(event.which);
if (event.which === 13 && event.shiftKey === false) {
console.log(str);
event.preventDefault();
} else {
var c = event.which;
str = str.concat(String.fromCharCode(event.which));
}
console.log('Formated Text', str);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea class="entry"></textarea>
I have a form in which I want users to only put alphabets, numbers
I want to restrict them from
Using the number as first value Eg. 1abc
Using Capitol letters Eg. 1ABc
Using Spaces Eg. 1 ab CD d5
I only want like abc1 OR a1bc OR f25fhgfh45w
I tried http://jsfiddle.net/m7QrG/506/ but it didn't help me out.
You can use RegExp /^\d|[A-Z\s]+/g to match digit at beginning of string or uppercase letters or space, remove i flag and $ anchor, use input event to also handle user pasting at <input> element
$('.alphaonly').on('input', function() {
$(this).val(function(i, val) {
return val.replace(/^\d|[A-Z\s]+/g, '');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input name="lorem" class="alphaonly">
After observing your question and your comments with #guest271314 I came up to with the solution:
$(function() {
var haveFirst = false;
$('.alphaonly').on('keypress', function (event) {
if( $(this).val().length === 0 ) {
haveFirst = false;
}
var regex = new RegExp("^[a-z0-9_]+$");
var first = new RegExp("^[a-z]+$");
var key = String.fromCharCode(!event.charCode ? event.which : event.charCode);
if(!first.test(key) && haveFirst == false){
event.preventDefault();
return false;
}else if(regex.test(key)){
haveFirst = true;
}
if (!regex.test(key)) {
event.preventDefault();
return false;
}
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input name="lorem" class="alphaonly">
In hoping it will work as you want!
I'm trying to make a jQuery method that would delete wanted chars from selected elements.
For example:
$("input").disallowChars(/\D/g);// should disallow input of all non-digit elements in input elements
This is how I thought to do it, but it doesn't seem to work:
$.fn.disallowChars = function(regexp){
this.keyup(function(){
var value = $(this).val();
value.replace(regexp, "");
$(this).val(value);
});
return this;
};
$("input").disallowChars(/\D/g);
I'm a total newbie at this, how can I make it work.
Thanks
You could use String.fromCharCode() and keypress event instead:
$.fn.disallowChars = function(regexp){
return this.keypress(function(e){
if(String.fromCharCode(e.which).match(regexp)) return false;
});
};
DEMO
BUT doesn't disable any characters to be paste in input using mouse or paste keyboard shortcut.
On modern browsers, you could use input event, or change keyup paste mouseup (ya mouseup, to handle dropped text too):
$.fn.disallowChars = function(regexp){
return this.on('input', function(){
this.value = this.value.replace(regexp, '');
});
};
BUT then once input value is replaced, text carret is put in end (or start depending browser behaviour) of string input.
DEMO
heres a handy routine I use to sanitize some input fields in a current project:
// REPLACE SELECTOR WITH YOUR ID(S) OR SELECTORS...
$('input').bind("change keyup", function() {
var val = $.trim($(this).val());
// READ UP ON REGEX TO UNDERSTAND WHATS GOING ON HERE... ADD CHARACTERS YOU WANT TO ELIMINATE...
var regex = /[":'/\+;<>&\\/\n]/g;
if (val.match(regex)) {
val = val.replace(regex, "");
$(this).val($.trim(val));
}
});
Heres another version I used recently:
$("#myField").on("keypress", function(event) {
// THIS ONLY ALLOWS A-Z, A-Z, 0-9 AND THE # SYMBOL... just change stuffToAllow to suit your needs
var stuffToAllow = /[A-Za-z0-9# ]/g;
var key = String.fromCharCode(event.which);
if (event.keyCode == 8 || event.keyCode == 37 || event.keyCode == 39 || stuffToAllow.test(key)) {
return true;
}
alert( key + ' character not allowed!');
return false;
});
$('input').keypress(function(e){
if(($(this).val().split('a').length - 1) > 0){
console.log($('input').val());
$('input').val($('input').val().replace('a', ''));
}
})
jsfiddle: http://jsfiddle.net/Ht8rU/
I want have only one "a" in input. I check if length a > 1 and next remove "a" from input, but this not working good. I would like remove only second a from this input. One "a" is allow.
Edit: Oh I see now... If you want to keep only the first a you can try this:
$('input').keypress(function(e) {
var key = String.fromCharCode(e.which);
if (/a/i.test(key) && /a+/i.test(this.value)) {
e.preventDefault();
}
});
Demo: http://jsfiddle.net/elclanrs/Ht8rU/6/
You have to check if the current letter being typed is a:
if (String.fromCharCode(e.which) == 'a')
But here's a simplified version. You don't need to use val() if you can use value, specially because it makes your code cleaner. Also you might want to check for A or a so a regex might be a better option. Here's the code:
$('input').keypress(function(e) {
var A = /a/gi,
letter = String.fromCharCode(e.which);
if (A.test(letter)) {
$(this).val(this.value.replace(A,''));
}
});
Demo: http://jsfiddle.net/elclanrs/Ht8rU/3/
I suggest using preventDefault to stop the key from being pressed:
$('input').keypress(function(e) {
if (e.keyCode === 97 && $(this).val().split('a').length > 1) {
e.preventDefault();
}
});
JSFiddle
This code may seem long and without any usefulness, but it works.
$('input').keyup(function(e) {
var e = $(this),
val = e.val(),
aPos = val.indexOf('a'),
spl1 = val.substring(0, aPos + 1),
spl2 = val.substring(aPos, val.length).replace(/a/gi, ''),
v = spl1 + spl2;
e.val(v);
});
Here is a working JSFiddle of this.
I would try something like this. Not sure how well supported is the input event currently, though.
(function() {
var elem = $('input');
var value = elem.val();
elem.bind("input propertychange", function(e) {
if (elem.val().split('a').length - 1 > 1)
elem.val(value);
else
value = elem.val();
});
})();
http://jsfiddle.net/Ht8rU/8/
When the user presses 'a' or 'A', you can check if there is one 'a' or 'A' already present, if there is one already then you don't add it to the input.
$('input').keypress(function(e){
if ((e.keyCode === 65 || e.keyCode === 97) & $(this).val().match(/a/gi) !== null) e.preventDefault();
})
Updated jsFiddle
Here's a modified version of your fiddle that works: http://jsfiddle.net/orlenko/zmebS/2/
$('input').keypress(function(e){
var that = $(this);
var parts = that.val().split('a');
if (parts.length > 2) {
parts.splice(1, 0, 'a');
that.val(parts.join(''));
} else {
// no need to replace
}
})
Note that we only replace the contents of the input if we have to - otherwise, constant rewriting of the contents will make it impossible to type in the midle or at the beginning of the text.
If you want to further improve it and make it possible to type at the beginning even when we are replacing the contents, check out this question about detecting and restoring selection: How to get selected text/caret position of an input that doesn't have focus?
I was able to find the solution for this in c# / .net but not for regular web html. If there's already an answer let me know and i'll close question.
How to create a text box that only will allow certain characters (ex. alphanumeric) based on a given regex (ex. [a-zA-Z0-9])? So if a user tries to enter anything else, paste included, it is removed or not allowed.
<input type="text" class="alphanumericOnly">
The basic function would be this:
string = string.replace(/[^a-zA-Z0-9]/g, '')
This would replace any character that is not described by [a-zA-Z0-9].
Now you could either put it directly into your element declaration:
<input type="text" class="alphanumericOnly" onkeyup="this.value=this.value.replace(/[^a-zA-Z0-9]/g, '')">
Or (as you used the class hint) you assign this behavior to every input element with the class alphanumericOnly:
var inputElems = document.getElemenstByTagName("input");
for (var i=0; i<inputElems.length; i++) {
var elem = inputElems[i];
if (elem.nodeName == "INPUT" && /(?:^|\s+)alphanumericOnly(?:\s+|$)/.test(elem.className) {
elem.onkeyup = function() {
this.value = this.value.replace(/[^a-zA-Z0-9]/g, '');
}
}
}
But it’s probably easier to do that with jQuery or another JavaScript framework:
$("input.alphanumericOnly").bind("keyup", function(e) {
this.value = this.value.replace(/[^a-zA-Z0-9]/g, '');
});
Example on how to allow alphanumeric chars and space (a-z, A-Z, 0-9 and space, others are eliminated as typed):
$('#some_input_field_id').unbind('change keyup paste mouseup').bind('change keyup paste mouseup', function(){if(this.value.match(/[^a-zA-Z0-9 ]/g)){this.value = this.value.replace(/[^a-zA-Z0-9 ]/g, '');}});
Eample on how to allow only lowercase alpha chars (a-z, others are eliminated as typed):
$('#some_input_field_id').unbind('change keyup paste mouseup').bind('change keyup paste mouseup', function(){if(this.value.match(/[^a-z]/g)){this.value = this.value.replace(/[^a-z]/g, '');}});
etc...
Assuming you have the input stored as the variable input...
input.onkeyup(function(e) {
this.value = this.value.replace(/\W/g, '');
}
After every keypress the value of the input will be stripped of any non-alphanumeric characters.
If you use a .replace method on the keyup event the input will flicker with the non-alphanumeric characters as they're typed, which appears sloppy and doesn't comply with OCD folks like myself.
A cleaner approach would be to bind to the keypress event and deny the characters before they even arrive at the input, like the following:
$('.alphanumericOnly').keypress(function(e){
var key = e.which;
return ((key >= 48 && key <= 57) || (key >= 65 && key <= 90) || (key >= 95 && key <= 122));
});
A list of basic keycodes can be found here if this particular set doesn't suit your specific needs.
I've noticed that at least in my case, with the paste and drop events, replacing the text wasn't working because at that point the value property of the input was still the previous one. So I did this:
With pure javascript:
function filterInputs() {
var that = this;
setTimeout(function() {
that.value = that.value.replace(/[^a-zA-Z0-9]/g, '');
}, 0);
}
var input = document.getElementById('theInput');
input.addEventListener('keyup', filterInputs);
input.addEventListener('paste', filterInputs);
input.addEventListener('drop', filterInputs);
input.addEventListener('change', filterInputs);
Try writing non-alphanumeric characters: <input type="text" id="theInput">
<br>You can use this input to write anything and copy-paste/drag & drop it into the other one: <input type="text">
With jQuery:
function filterInputs() {
var that = this;
setTimeout(function() {
that.value = that.value.replace(/[^a-zA-Z0-9]/g, '');
}, 0);
}
$('#theInput').on('keyup paste drop change', filterInputs);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Try writing non-alphanumeric characters: <input type="text" id="theInput">
<br>You can use this input to write anything and copy-paste/drag & drop it into the other one: <input type="text">