js backspace and counting how many digits - javascript

i have this code for counting how many digits where entered
var tnnod=0;
function telephone(e) {
if (tnnod<10) {
var key;
var keychar;
if (window.event) {
key = window.event.keyCode;
}
else if (e) {
key = e.which;
}
else {
return true;
}
keychar = String.fromCharCode(key);
if ((key==null) || (key==0) || (key==8) || (key==9) || (key==13) || (key==27) ) {
return true;
}
else if ((("0123456789").indexOf(keychar) > -1)) {
tnnod+=1;
return true;
}
else if (keychar == "-") {
return true;
}
else
return false;
}
else
return false
}
but how do i remove 1 from the counter each time the backspace was hitted and the char that was deleted was a digit and not "-"
i have tried getting the key == 8 to do something but hitting the backspace doesn't really return anything for some reason
what can be the problem?

You don't have to detect specifically the backspace keypress. Try this:
var tn_count = 0;
function telephone(ev) {
var el = document.getElementById("telephone_number");
if(tn_count < 10) {
var key, keychar;
if(window.event) {
key = window.event.keyCode;
} else {
key = ev.which;
}
keychar = String.fromCharCode(key);
}
if(!keychar.match(/\d|-/)) { // only allow digits or "-"
return false;
}
// clean up any non-digit chars that get in here somehow
el.value = el.value.replace(/[A-Za-z]+/, '');
tn_count = el.value.replace("-",'').length; // get the digit length
return true;
}
The basic difference here is that instead of adding 1 every time the key is pressed, just updated tn_count to be the total count of all digit characters in the field. You can probably do some more cleanup just to be safe, but this should get you started.

I think it's a bad idea to count keystrokes for something like that. We're talking about input into a text field, right? What will you do if the user does a paste of some string from the clipboard? What if he uses the mouse to mark some text and delete it? Replace it with one character?
I think it would make a lot more sense to just look at the text from the text field and (if necessary) do some fiddling to ensure proper syntax. Let the user enter whatever he wants, if you find garbage characters you can just replace the text with one that doesn't have those characters. You can also trim the field at this time (no leading or trailing spaces). Also, keeping accurate track of the length becomes as easy as asking for the length of the string returned from the field.

A few thoughts -
Would it be possible to use 3 fields instead of 1? Then you could add the dashes later.
If you want to use your current method, you might keep a counter of the dashes that have been typed. Then, on each key stroke, check to see how many dashes are left. If it's different than the previous count, you know they've deleted the dashes.
I think it needs to be a bit more robust. What if they put a dash in an odd place within the string?
You could also prevent the user from entering all non-numeric characters and insert the dashes at each point of separation. So, insert a dash after 3 and 6 numbers as they are typing.

Could you just count the length of the string and use that value? Something like the following:
function getLen(el) {
return el.value.replace('-', '').length;
}
alert(getLen(document.getElementById('telephone_number')));

Related

Restrict text input to number groups separate by a non-consecutive character

I've been doing a lot of searching, chopping and changing, but I'm...slightly lost, especially with regards to many of the regex examples I've been seeing.
This is what I want to do:
I have a text input field, size 32.
I want users to enter their telephone numbers in it, but I want them to enter a minimum of 10 numbers, separated by a single comma. Example:
E.g. 1
0123456789,0123456789 = right (first group is >=10 numbers, second group = >=10 numbers & groups are separated by a single comma, no spaces or other symbols)
E.g. 2
0123456789,,0123456789 = wrong (because there are 2 commas)
E.g. 3
0123456789,0123456789,0123456789 = right (same concept as E.g. 1, but with 3 groups)
I've got the following, but it does not limit the comma to 1 per 10 numbers, and it does not impose a minimum character count on the number group.
$(document).ready(function(){
$("#lastname").keypress(function (e) {
//if the letter is not digit then display error and don't type anything
if (e.which != 8 && e.which != 0 && String.fromCharCode(e.which) != ','
&& (e.which < 48 || e.which > 57)) {
//display error message
$("#errmsg").html("Digits Only").show().fadeOut("slow");
return false;
}
});
});
Preferably, I'd like to warn the user of where they are going wrong as well. For example, if they try to enter two commas, I'd like to specifically point that out in the error, or if they havent inserted enough numbers, i'd like to specifically point that out in the error. I'd also like to point out in the error when neither a number or a comma is inserted. I'd like to ensure that the tab, and F5 keys are not disabled on the keyboard as well. And very importantly, I'd like to specifically detect when the plus or addition key is used, and give a different error there. I think I'm asking for something a little complex and uninviting so sorry :/
The example code I provided above works pretty well across all browsers, but it doesn't have any of the minimum or maximum limits on anything I've alluded to above.
Any help would be appreciated.
As far as a regex that will check that the input is valid (1-3 phone numbers of exactly 10 digits, separated by single commas), you can do this:
^\d{10}(,\d{10}){0,2}$
Try like the below snippet without Regex
var errrorMessage = '';
function validateLength (no) {
if(!no.length == 10) {
return false;
}
return true;
}
function validatePhoneNumbers (currentString, splitBy) {
if(currentString) {
var isValid = true,
currentList = currentString.split(splitBy);
// If there is only one email / some other separated strings, Trim and Return.
if(currentList.length == 1) {
errrorMessage = 'Invalid Length in Item: 1';
if(validateLength( currentString.trim() )) isValid = false;
}
else if(currentList.length > 1) {
// Iterating mainly to trim and validate.
for (var i = 0; i < currentList.length; i++) {
var listItem = currentList[i].trim();
if( validateLength(listItem ) ) {
isValid = false;
errrorMessage = 'Invalid Length in Item:' + i
break;
}
// else if for some other validation.
}
}
}
return isValid;
}
validatePhoneNumbers( $("#lastname").val() );

How to determine if user is beginning new word in JS?

How would you, with JS or jQuery, determine if what the user is typing is a new word?
What I want to do:
I am writing a documentation tool with autocompletion for different types. If you type f.e. # it will populate Java Classes in a box, # would populate test classes, etc. Now I don't want to populate these values, if the user is writing something like an email like yourname#domain.com. So I need the values to populate only when it's the beginning of the word.
I am aware of keydown, keyup events, etc. I just don't know how to check for this certain kind of event properly.
One way would be to save every typed letter in a variable and then check if the previous "letter" was a space and if it was, we know it's a new word. Is this the best/most efficient way to do this?
One way is to check what's before the # in the input box, using selectionStart:
onload = function() {
var io = document.getElementById("io");
io.onkeypress = function(e) {
if(e.charCode == 64 && (
io.selectionStart == 0 || io.value[io.selectionStart-1].match(/\s/)))
document.getElementById("ac").innerHTML = "autocomplete!";
else
document.getElementById("ac").innerHTML = "";
}
}
<input id="io">
<div id="ac"></div>
Try this JSFiddle. I'm performing the check like so:
var text = $("#test").val();
if (text.length == 0 || text.charAt(text.length - 1).match(/[\s\b]/)) {
$("#result").html("new word");
} else {
$("#result").html("no new word");
}
You can easily adapt the .match() pattern if you like to include other characters as "whitespaces" (e.g. curly braces) for your Editor.
Assuming text is entered in a text input with id="txtchangedetection":
$("#txtchangedetection").change(function(){
console.log("The text has been changed.");
});
/*This is `JQuery`*/
I've understood you want to detect word changes in the input. Please precise if I'm wrong. What do you mean by 'new word' ?
One solution will be like this :
1- declare a variable "newWord = true"
2- with keydown event check if the key pressed is a space
if YES : newWord = true
if NO : newWord = false
var newWord=true;
$("#textarea").keydown(function(e){
if(e.keyCode == 32){
newWord=true;
}else{
newWord=false;
switch(e.keyCode){
//work to do
}
}
})
use keypress on your input field... populate the array inside the if with your special chars
if(prev == 13 || prev == 32 || $('#doc').val().length==0 || prev==null){
listen = true;
}else{
listen = false;
}
prev = e.which;
if(listen && $.inArray(String.fromCharCode(e.which),["#","#"]) != -1){
e.preventDefault();
alert("populate box here");
listen = false;
prev = null;
}
the fiddle https://jsfiddle.net/6okfqub4/

Javascript Regex to limit Text Field to only Numbers (Must allow non-printable keys)

I have received PHP/JS code from previous developer and I need to add number validation to a Mobile Number field. I already have the HTML validation in place but I need to add that if someone presses an invalid key, that it doesn't get displayed only to highlight the field later in red because it contains invalid input.
I've seen many regex's used and tried them but they had an either/or effect from what I need which is: If a letter or special character is entered, do not accept and do not display, all other input (digits, keys) is accepted (I need the invalid character not be displayed at all, not displayed and then erased). The regex that is working the most now is this:
function filterNonDigits(evt)
{
var event = evt || window.event;
var keyentered = event.keyCode || event.which;
keyentered = String.fromCharCode(keyentered);
//var regex1 = /[0-9]|\./;
var regex2 = /^[a-zA-Z.,;:|\\\/~!##$%^&*_-{}\[\]()`"'<>?\s]+$/;
if( regex2.test(keyentered) ) {
event.returnValue = false;
if(event.preventDefault) event.preventDefault();
}
When I used the commented regex1 (with the IF condition reversed), naturally it limited input to only digits thus preventing all keys such as Delete, BackSpace, etc. When using regex2, I still can't press Delete or the digits from the numpad.
So my question is, can the above code be modified to accept only digits but also allow keys? Another important point is that I need a method that doesn't use keycodes (8, 24 etc) for those key, in order to make sure all keyboard types can be used.
New Update:
So my solution is as follows: If the "oninput" property exists, I use the solution provided by Ehtesham and if it doesn't, the backup uses the solution provided by Rohan Kumar. So it's something like this:
if (obj.hasOwnProperty('oninput') || ('oninput' in obj))
{
$('#mobileno').on('input', function (event) {
this.value = this.value.replace(/[^0-9]/g, '');
});
}
else
{
$('#mobileno').on('keypress',function(e){
var deleteCode = 8; var backspaceCode = 46;
var key = e.which;
if ((key>=48 && key<=57) || key === deleteCode || key === backspaceCode || (key>=37 && key<=40) || key===0)
{
character = String.fromCharCode(key);
if( character != '.' && character != '%' && character != '&' && character != '(' && character != '\'' )
{
return true;
}
else { return false; }
}
else { return false; }
});
}
Thanks.
The best method here is to use input event which handles all your concerns. It is supported in all modern browsers. With jQuery you can do like following. Handles all cases pasting the value with mouse/keyboard backspace etc.
$('.numeric').on('input', function (event) {
this.value = this.value.replace(/[^0-9]/g, '');
});
See it here
You can check if input event is supported by checking if the input has this property if not you can use onkeyup for older browsers.
if (inputElement.hasOwnProperty('oninput')) {
// bind input
} else {
// bind onkeyup
}
A nice solution is described in a previous post:
jQuery('.numbersOnly').keyup(function () {
this.value = this.value.replace(/[^0-9\.]/g,'');
});
Try it like,
CSS
.error{border:1px solid #F00;}
SCRIPT
$('#key').on('keydown',function(e){
var deleteKeyCode = 8;
var backspaceKeyCode = 46;
if ((e.which>=48 && e.which<=57) ||
(e.which>=96 && e.which<=105) || // for num pad numeric keys
e.which === deleteKeyCode || // for delete key,
e.which === backspaceKeyCode) // for backspace
// you can add code for left,right arrow keys
{
$(this).removeClass('error');
return true;
}
else
{
$(this).addClass('error');
return false;
}
});
Fiddle: http://jsfiddle.net/PueS2/
Instead of checking for the event keyCode, why don't you just check for changes inside the actual input and then filter out non-numbers?
This example uses keyup so that it can read what was actually entered, which means the character is briefly displayed and then removed, but hopefully you get my gist. It might even give the user feedback that the character is not allowed. Either way I think this is the easiest setup, let me know if you need more help fleshing this out.
function filterNonDigits(evt)
{
var event = evt || window.event;
var val = event.target.value;
var filtered = val.replace(/[^0-9]/g, '');
if(filtered !== val) {
event.target.value = filtered;
event.target.className += " error";
}
}
http://jsfiddle.net/mEvSV/1/
(jquery used solely to easily bind the keyup function, you won't need it for your actual script)
/\d/ is equivalent to the above described /[0-9]/. src: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions#special-digit
This is a bit more concise...
this.value = this.value.replace(/\D/gm, '');

How can I limit a textbox to have less than 3 commas in it?

For example we have a textbox which is for tags for a blog. What I want is I want to limit number of tags to be limited.
For instance, "web hosting,php,windows8".
When the user tries to type another one to textbox which he will start with comma, the textbox won't let him write it.
In your keypress handler, capture the event object and do;
if (event.which == 44 && $(this).val().split(",").length > 2) {
event.preventDefault();
}
See it in action here; http://jsfiddle.net/5L7mU/
We can split this problem into 3 smaller problems.
First, we need a way to stop the user from writing stuff into the textbox. When you hook a callback on keypress, the event passed has a method called preventDefault which should do the job. So to block all input:
$("input").keypress(function(event) {
event.preventDefault();
});
Now, to check how many comas there already are in the textbox, we can use regex. The match function will return null instead of an empty array if there are no matches so we gotta check for that.
$("input").keypress(function(event) {
var matches = $(this).val().match(/,/g);
var count = 0;
if (matches)
count = matches.length;
console.log(count);
});
Finally, we need to be able to check if the user typed in a coma. The event objectwill have a property called which that contains the key code of the character entered. With a little bit of exploring, you can find out that the key code for coma is 44.
$("input").keypress(function(event) {
if (event.which == 44)
event.preventDefault();
});
So if we put it all together:
$("input").keypress(function(event) {
var matches = $(this).val().match(/,/g);
var count = 0;
if (matches)
count = matches.length;
if (count >= 2 && event.which == 44)
event.preventDefault();
});
http://jsfiddle.net/4wn5W/
$(document).ready(function(){
$('#textbox').keypress(function(e){
var text = $(this).val();
if(text.split(',').length>3){
return false;
}else if(e.which==44&&text.split(',').length>2){
return false
}
});
});
Fiddle:
http://jsfiddle.net/L4X4C/

Allow only numeric input in a text input, and allow a hyphen as an optional first character

I need to automatically clean user entry into a text input - to only allow numbers, except for the first character, which could be a number or a hyphen.
So, for example, if the user types 138a29 it would be automatically updated to 13829.
I was using an onKeyPress event to check the keyCode to allow only numbers, but that's proved to be a little difficult to truly allow only numbers without breaking arrow keys, backspace keys, etc in some browsers. And now there is a new requirement to allow a hyphen(-) as an optional first character, but a hyphen is not valid anywhere else in the string.
I have the Prototype library to use for my particular project, but no jQuery.
The simplest way to do this is to avoid the keyCode and use the textbox's value on keyup. Something like this...
Event.observe('myInput', 'keyup', function(){
var value = this.value, first;
if(value.length == 0)
return;
first = value.charAt(0);
value = value.replace(/[^0-9]/g,'');
if(first == '-')
value = first + value;
this.value = value;
return true;
});
Try this
<script type="text/javascript">
function whatKey(e) {
var thetext = document.getElementById('tt'); // Current value
var theKey = String.fromCharCode(e.keyCode); // key entered
var combval = thetext.value + theKey; // Result would be this
return (!isNaN(combval) || combval=='-'); // if result OK, accept key
}
</script>

Categories

Resources