Removing unwanted characters from textbox with JQuery - javascript

What I would like to get some input on is how to remove certain characters from a textbox (or textarea) with JQuery. I have the code in C# but I can´t seem to translate that to JQuery javascript. My problem is that I don´t know how to get the value from a textbox as a character array which I then can loop through and compare against a given set of unwanted characters.
This is how "far" I have come in JQuery:
$("input[type=text], textarea").change(function() {
// code here
});
This is my code in C#:
for (int i = 0; i < charArray.Length; i++)
{
current = charArray[i];
if ((current == 0x9) ||
(current == 0xA) ||
(current == 0xD) ||
((current >= 0x20) && (current <= 0xD7FF)) ||
((current >= 0xE000) && (current <= 0xFFFD)))
_validXML.Append(current);
}
return _validXML.ToString().TrimEnd((char)32, (char)160) ;
UPDATE:
I went with a combination of some answers below (I will upvote them) and my final JQuery looks like this and works:
$(document).ready(function() {
$(":text, textarea").change(function() {
var text = "";
var arr = $(this).val()
$.each(arr, function(i) {
var c = arr.charCodeAt(i);
if ((c == 0x9) ||
(c == 0xA) ||
(c == 0xD) ||
(c >= 0x20 && c <= 0xD7FF) ||
(c >= 0xE000 && c <= 0xFFFD))
{
text += arr.charAt(i);
}
});
$(this).val(text);
});
});
Thanks all!

Would't this be the case for regular expressions, like:
$("input[#type='text'], textarea").change(function() {
this.value = this.value.replace(/[^\w\d]+/gim,"");
});

Textarea:
<textarea id="item" name="item" rows="5" cols="80">Some text in here</textarea>
jQuery code:
var text = $('#item').val();
var newtext = "";
for (var i = 0; i < text.length; i++) {
var c = text.charCodeAt(i);
if ((c == 0x9) || (c == 0xA) || (c == 0xD) ||
(c >= 0x20 && c <= 0xD7FF) ||
(c >= 0xE000 && c <= 0xFFFD)) {
newtext += text[i];
}
}
$('#item').val(newtext);
This has actually very little to do with jQuery, methinks, except to access the text data and set it again.

You can use the charCodeAt() method combined with the length property of strings to loop through the characters in the string.
Something like:
$("input[type=text], textarea").change(function() {
var text = $(this).val()
for(var i = 0; i < text.length; ++i) {
var currentChar = text.charCodeAt(i);
// Do something with it...
});
My initial version used charAt(), but since it looks like you're dealing with Unicode code points, charCodeAt() is more appropriate.

Use an event observer (onkeydown / onkeypress / onkeyup) on the input/textarea, get the key pressed, if the key is an unwanted character, stop the event from happening.
$("input[type=text], textarea").observe('keypress', function(e) {
var keynum;
if(window.event)
{
keynum = e.keyCode
}
else if(e.which)
{
keynum = e.which
}
if(keynum == '13' || keynum == 'something else' || [...])
{
Event.stop(e);
}
});

to get the value of textarea try:
$('input[type=textarea]').change(function(){
var value = $(this).val();
...........
});
to remove unwanted character try this example .. i copy from the jquery documentation (jQuery.grep())
var arr = [ 1, 9, 3, 8, 6, 1, 5, 9, 4, 7, 3, 8, 6, 9, 1 ];
$("div").text(arr.join(", "));
arr = jQuery.grep(arr, function(n, i){
return (n != 5 && i > 4);
});
$("p").text(arr.join(", "));
arr = jQuery.grep(arr, function (a) { return a != 9; });
$("span").text(arr.join(", "));

I prefer to stop the character from getting entered in the first place, using this type of javascript function (from my shady past):
each input control has something like this on it:
onkeypress='checkKey(this,"a-zA-Z0-9","N","10");'
the function looks like:
//****************************************************************************
// Function: checkKey()
// Author: Ron Savage
// Date: 10-11-2004
//
// Description: This function tests reg exp syntax.
//****************************************************************************
function checkKey(textControl, reExpr, allCaps, maxlen)
{
popupMessage.hide();
keyStr = String.fromCharCode(event.keyCode);
textLength = textControl.value.length;
if (allCaps == 'Y')
{
keyStr = keyStr.toUpperCase();
event.keyCode = keyStr.charCodeAt(0);
}
if ( reExpr != '' )
{
reString = '[^' + reExpr + ']';
re = new RegExp(reString, 'g');
//alert('RE: ' + reString);
result = keyStr.match(re);
if (result)
{
beep();
event.returnValue = false;
showPopupMessage(textControl, result.toString() + ' not allowed!');
}
}
if ( textLength > maxlen )
{
beep();
event.returnValue = false;
showPopupMessage(textControl, 'Max length [' + maxlen + '] exceeded!');
}
//alert('Key: ' + keyStr + ' code: ' + event.keyCode);
}

Related

Date validation - Go to next input field once number of characters entered

This is someone else's code and I am quite new to JS so finding it quite difficult to understand.
I'm trying to auto tab to the next input once the maximum limit has been reached.
The problem I'm having is that the input for year is tabbing before the full year has been fully entered.
If someone could point me to the right direction that would be of great help.
JS Bin:
https://jsbin.com/wazarezufi/edit?js,output
"use strict";
var parts = el.find('input');
function constructor(el) {
console.log('running');
$('input').on('keyup', _.bind(onKeyup, this))
.on('keypress', _.bind(onKeypress, this))
.on('focus', focus)
.on('paste', _.bind(paste, this));
}
function paste(evt) {
// allows pasting of dates in
var str = evt.originalEvent.clipboardData.getData('text/plain'),
bits;
if (str && (bits = /(\d\d)[\/\\.-]?(\d\d)[\/\\.-]?(\d\d\d\d)/.exec(str))) {
parts.each(function (idx) {
$(this).val(bits[idx + 1]);
})
return false;
}
}
function onKeypressDef(e) {
var el = e.target;
var val;
// find the target in our list
for (var idx = 0; idx < parts.length; idx++) {
if (parts[idx] === el) break;
}
if ((val = $(el).val()).length == 2) {
if (idx < parts.length - 1) {
parts[idx + 1].select();
}
}
}
function focus() {
$(this.select());
};
function onKeyup(e) { // needed to trap the backspace
console.log('keyup');
if (e.which === 8) {
onKeypress.call(this, e);
}
}
function onKeypress(e) {
var self = this;
var evt = e;
if ((evt.which > 32) && (/\D/.test(String.fromCharCode(evt.which)))) return false; // only let numeric chars through
_.defer(function () {
onKeypressDef.call(self, evt);
});
}
constructor();
Thanks
You could have a data attribute where you could specify the length of the input, like so:
<input placeholder="YYYY" data-length="4">
Then update you javascript to check for this attribute and if not found, then use 2 as the default.
if ((val = $_el.val()).length == ($_el.data('length') || 2)) {}
The problem is doing this for any input:
if ((val = $(el).val()).length == 2)
You should check (by id, for example) which input triggered the event and compare the length to 2 or 4 depending in the case.
Have updated the fiddle -- https://jsbin.com/vojojufabe/edit?js,output
The issue was that the length was being checked when the data is entered and when lenght is 2 it jumps to next input, have added isyear data attribute, and checked it for lenght to be of 4 characters
if (!isYear && val=== 2) {
if (idx < parts.length - 1) {
parts[idx + 1].select();
}
}
if (isYear && val=== 4) {
if (idx < parts.length - 1) {
parts[idx + 1].select();
}
}
You can achieve this by adjusting your input length check with something as follows:
var l = 2
if (el.id === 'input__date-year-arriveInUk') {
l = 4
}
if ((val = $(el).val()).length == l) {...
You can check whether the id of the current input is the one of your date input and focus the next input after a String of length 4 is entered.

auto slash in date field to remain permanent using javascript

I can add auto slash to the date field.But when I hit backspace, I need the backslash to remain where it is.
var keycode = event.which,
value = $(current).val(),
position1 = 3,
position2 = 6;
if((value.length === (position1 - 1)) ||
(value.length === (position2 - 1))){
if (keycode === 8) {
value = value + '/';
}
}
You can try jsfiddle from this answer
var format = "mm/dd/yyyy";
var match = new RegExp(format
.replace(/(\w+)\W(\w+)\W(\w+)/, "^\\s*($1)\\W*($2)?\\W*($3)?([0-9]*).*")
.replace(/m|d|y/g, "\\d"));
var replace = "$1/$2/$3$4"
.replace(/\//g, format.match(/\W/));
function doFormat(target)
{
target.value = target.value
.replace(/(^|\W)(?=\d\W)/g, "$10") // padding
.replace(match, replace) // fields
.replace(/(\W)+/g, "$1"); // remove repeats
}
$("input[name='birthdate']:first").keyup(function(e) {
if(!e.ctrlKey && !e.metaKey && (e.keyCode == 32 || e.keyCode > 46))
doFormat(e.target)
});
Update
Try this one fiddle that uses HTML5

Best way to check if a character is a number of letter in javascript?

In javascript whats the best way to check if a character (length 1), is a number (i.e. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9) or a letter (i.e. A to Z, a to z)?
Thanks
Why not:
function isNumber(i) {
return (i >= '0' && i <= '9');
}
function isLetter(i) {
return ((i >= 'a' && i <= 'z') || (i >= 'A' && i <= 'Z'));
}
I wrote a little test case for you, at least for the numeric checking function.
Considering the fact that all functions returns true with either a numberic 1 or a string '1' literal, using an Array seems to be the fastest way (at least in Chrome).
var isNumericChar = (function () {
var arr = Array.apply(null, Array(10)).map(function () { return true; });
return function (char) { return !!arr[char]; };
})();
However, if you accept that it might return false for 1, the switch statement is then significantly faster.
Try this.
function validate_string() {
var str = "a"; //change to desired value;
var regX = new RegExp("([0-9A-Za-z])");
var ans = false;
if(str.length == 1) {
ans = regX.test(str);
}
return ans;
}
Edit: Refactored my answer.
function validateString(char) {
let regx = new RegExp(/^[0-9A-Za-z]{1}$/g);
return regx.test(char);
}
validateString('4'); // true
validateString('as'); // false
validateString(''); // false
validateString(); // false
Maybe try something like this
var sum = 0; //some value
let num = parseInt(val); //or just Number.parseInt
if(!isNaN(num)) {
sum += num;
}
This blogpost sheds some more light on this check if a string is numeric in Javascript | Typescript & ES6
You can check for the type of the variable
function checkType(input){
console.log(typeof input)
}
checkType(1234); //number
checkType('Hello') //string
Here is an updated version
function checkType(i){
var input = i.toString(); //convert everything to strings to run .lenght() on it
for(var i=0; i<input.length; ++i){
if(input[i] >= '0' && input[i] <= '9'){
console.log(input[i]+' is a number');
}else if((input[i] >= 'a' && input[i] <= 'z') || (input[i] >= 'A' && input[i] <= 'Z')){
console.log(input[i]+' is a letter');
}
}
}
checkType('aa9fgg5')

Javascript - handling keypresses in order?

I have a simple "onKeyUp" Javascript routine that is supposed to handle adding dashes to an input field to format a phone number, turning "1234567890" into "123-456-7890". However, if the user types too fast the routine apparently doesn't fire, or the event gets lost, I'm not sure. But in that case, the dashes don't get inserted.
Can anyone suggest a fix for this? Here's the routine:
function(event, field) {
// Don't add dashes if user pressed backspace
if (event.keyCode != 8 ) {
if (field.value.length == 3 || field.value.length == 7) {
field.value = field.value + "-";
}
}
};
SOLUTION
var dashes = function(event, field) {
if (event.keyCode != 8 ) {
var arr = field.value.split(''),
l = arr.length;
if(l > 2 && arr[3] != "-") arr.splice(3, 0, "-");
if(l > 6 && arr[7] != "-") arr.splice(7, 0, "-");
field.value = arr.join('');
}
};
var input = document.getElementById('in');
input.addEventListener('keyup',function(event){
dashes(event, input);
});

convert alphabets to coresponding numbers

i have to convert alphabets to corresponding numbers like i have a data like "DRSG004556722000TU77" and the index for A is 10, B is 11, C is 12 and so on up to Z is 35.
any helping tips??
here is the javascript which return me ascii code but i want to get the above indecies for respective alphabet
var string = DRSG004556722000TU77;
function getColumnName(string) {
return ((string.length - 1) * 26) + (string.charCodeAt(string.length - 1) - 64);
}
document.write( getColumnName(string) );
This may help
var output = [], code, str = 'DRSG004556722000TU77',i;
for(i in str){
code = str.charCodeAt(i);
if(code <= 90 && code >= 65){
// Add conditions " && code <= 122 && code >= 97" to catch lower case letters
output.push([i,code]);
}
}
Now ouput contains all letters codes and their corresponding indexes
var string = 'DRSG004556722000TU77';
function getColumnName(string) {
var recode = new Array(), i, n = string.length;
for(i = 0; i < n; i++) {
recode.push(filter(string.charCodeAt(i)));
}
return recode;
}
function filter(symbol) {
if ((symbol >= 65) && (symbol <= 90)) {
return symbol - 55;
} else if ((symbol >= 48) && (symbol <= 57)) {
return symbol - 48;
}
}
document.write(getColumnName(string));

Categories

Resources