auto slash in date field to remain permanent using javascript - 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

Related

Using regex to restrict input in textbox [duplicate]

This question already has answers here:
HTML input that takes only numbers and the + symbol
(7 answers)
Closed 5 years ago.
/^+{0,1}(?:\d\s?){11,13}$/ this regex allows + at first place only and numbers only...
on keypress I want user should only be able to type + at first and digits that what above regex validates But code always goes to if part..why regex not working in this scenario
function ValidatePhone(phone) {
var expr = /^\+?(?:\d\s?){11,13}$/;
return expr.test(phone);
}
var countofPlus = 0;
$("#phone").on("keypress", function (evt) {
if (evt.key == "+")
{
countofPlus = countofPlus + 1;
if (countofPlus > 1 || this.value.length >= 1) {
return false;
}
else return true;
}
var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode > 31 && charCode != 43 && charCode != 32 && charCode != 40 && charCode != 41 && (charCode < 48 || charCode > 57))
return false;
return true;
});
$("#phone").on("keyup", function (evt) {
debugger;
if (evt.key == "+") {
countofPlus--;
return true;
}
});
Adapting an answer from HTML input that takes only numbers and the + symbol to your use-case yields the following (IE-)compatible code:
// Apply filter to all inputs with data-filter:
var inputs = document.querySelectorAll('input[data-filter]');
for (var i = 0; i < inputs.length; i++) {
var input = inputs[i];
var state = {
value: input.value,
start: input.selectionStart,
end: input.selectionEnd,
pattern: RegExp('^' + input.dataset.filter + '$')
};
input.addEventListener('input', function(event) {
if (state.pattern.test(input.value)) {
state.value = input.value;
} else {
input.value = state.value;
input.setSelectionRange(state.start, state.end);
}
});
input.addEventListener('keydown', function(event) {
state.start = input.selectionStart;
state.end = input.selectionEnd;
});
}
<input id='tel' type='tel' data-filter='\+?\d{0,13}' placeholder='phone number'>
Above code takes copy & pasting, selecting, backspacing etc. into account where your current implementation fails.
Also, I modified the given regex to \+?\d{0,13} so it allows for incomplete input. Use HTML5 form validation to validate the final result.
I think this regex is being applied only to the char code i.e. a string of length 1. In this case regex will always fail.
Instead, try running the regex test on the input value.

Limit numbers before and after decimal point on input number

How to limit numbers for before and after the decimal point, something like 123.123 , so it can have max 3 numbers before . and max 3 numbers after .
<div class="form-group">
<input type="number" class="form-control" name="ta" id="ta" placeholder="ta" ng-model="ta.kol" ng-maxlength="15"/>
<p ng-show="taForm.kol.$error.maxlength" class="help-block">Max 15 symbols !</p>
</div>
You can add a onchange event on the input field and call a function that validates the current input value using regex and communicate same to the user.
Regex : ^[0-9]{0,3}.?[0-9]{0,3}$
JS Code to validate:
function validateNumberInput(inputNumber){
return number.search(/^[0-9]{0,3}.?[0-9]{0,3}$/) == 0 ? true : false;
}
Also you can write a directive in angular that can handle the same.
This can be solved with a simple piece of javascript if you just add an Event Listener to the input and then split the input on the decimal point you can then check the length of both parts and act accordingly.
https://jsfiddle.net/pk07net6/
function checkNumbers()
{
console.log(this.value);
var numbers = this.value.split('.');
var preDecimal = numbers[0];
var postDecimal = numbers[1];
if (preDecimal.length>3 || postDecimal.length>3)
{
alert("Max 3 numbers before and after the decimal point.")
this.select();
}
}
//ADD LISTENER TO INPUT
var input = document.getElementById("numberInput");
console.log(input);
input.addEventListener("change", checkNumbers)
You can use ng-pattern with a regex:
<input ng-pattern="/^[0-9]{1,3}(\.\d{0,3})?/" />
docs: https://docs.angularjs.org/api/ng/directive/ngPattern
For the fraction its pretty easy as you can use Angular number filter. As for the number before the digit you should create a filter like this :
app.filter('beforeDigit', function ($filter) {
return function (input) {
if (input>1000)
return (input % 1000)
elseif(input<1000)
return input;
};
});
So in the end you will end up with something like this :
{{val | filter:{number:3}, filter:beforeDigit }}
After hours of work, I create java-script function which work on keypress event. Number can be 8 characters before decimal separator and 2 character after decimal separator.
https://codepen.io/dumbelovic/pen/bvdXXq
function BeforeAfter(e, obj) {
sepDec = "."
var keycode;
var fieldval = obj.value;
if (window.event) keycode = window.event.keyCode;
else if (e) { keycode = e.which; }
else { return true; }
// denided first charatcter to be zero
if (fieldval == "" && keycode == 48)
return false;
// denided first character to be decimal point
if (fieldval == "" && (keycode == 44 || keycode == 46))
return false;
// enter first decimal point,
// but every next try to eneter decimal point return false
if (fieldval != "" && ((keycode == 44 || keycode == 46))) {
if (fieldval.indexOf(sepDec) < 0) {
var newValue = fieldval + sepDec;
$(obj).val(newValue);
}
return false;
}
var splitfield = fieldval.split(sepDec);
var beforeDecimalPoint;
var afterDecimalPoint;
if (splitfield.length == 1) {
beforeDecimalPoint = splitfield[0];
afterDecimalPoint = "";
}
else if (splitfield.length == 2) {
beforeDecimalPoint = splitfield[0];
afterDecimalPoint = splitfield[1];
}
if (beforeDecimalPoint.length == 8 && keycode != 8 && keycode != 0) {
if (obj.selectionStart >= 0 && obj.selectionStart <= 8)
return false;
}
if (afterDecimalPoint.length == 2 && keycode != 8 && keycode != 0) {
if (obj.selectionStart >= beforeDecimalPoint.length + 1 && obj.selectionStart <= beforeDecimalPoint.length + 1 + 2)
return false;
}
return true;
}

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);
});

JavaScript: Restricting fields - cannot remove special symbols

I am trying to restrict an input text to numbers only by checking it in a setInterval and removing the chars that are not numbers. Now so far this works relatively alright, however I am not able to remove "special symbols". For example if I input the Spanish accent symbol ' or symbols like ˇ that should be over a char, it resets the field and the value is not assigned again despite the fact that the symbol gets removed from the string (if I log the string, I can see it is).
Example:
Typing 123a => 'a' removed, input contains 123
Typing 123ˇ => input contains an empty string, despite the fact that the 'text' string
contains 123 and has a length of 3.
Typing 123 and pasting ˇ after it => ˇ removed, input contains 123
This seems like it has something to do with the fact that the special symbols are not ...self-standing (?) and need to be over a char that should be inputted next. Some ideas how to solve it?
Thank you.
I have the following HTML:
<body>
<input type="text" id="input_field">
</body>
And the JS:
$("#input_field").focus(function(e) {
console.log("got focus"+$(this).val());
var obj = this;
intID = setInterval(function() {restrictNumbers(obj)}, 10);
});
$("#input_field").blur(function(e) {
console.log("got blur")
clearInterval(intID);
});
function restrictNumbers(field) {
var text = $(field).val();
var caretPos;
var modified = false;
if(text.length > 0) {
for(var i=0; i<text.length; i++) {
if(isNaN(text.charAt(i))) {
modified = true;
caretPos = field.selectionStart - 1;
text = text.replace(text.charAt(i), "");
i--;
}
}
$(field).val(text);
if(modified) {
modified = false;
field.setSelectionRange(caretPos, caretPos);
}
}
}
JSfiddle example: http://jsfiddle.net/AvMZ5/
You can use this:-
jQuery.fn.ForceNumericOnly =
function()
{
return this.each(function()
{
$(this).keydown(function(e)
{
var key = e.charCode || e.keyCode || 0;
// allow backspace, tab, delete, arrows, numbers and keypad numbers ONLY
// home, end, period, and numpad decimal
return (
key == 8 ||
key == 9 ||
key == 46 ||
key == 110 ||
key == 190 ||
(key >= 35 && key <= 40) ||
(key >= 48 && key <= 57) ||
(key >= 96 && key <= 105));
});
});
};
You can then attach it to your control by doing:
$("#yourTextBoxName").ForceNumericOnly();
Source:- https://gist.github.com/wholypantalones/3083362

Removing unwanted characters from textbox with JQuery

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);
}

Categories

Resources