validation script losing characters - javascript

the script below should validate the user input each typed character at once, but it's losing characters, and it's always the character after a symbol (ex.: if I type 14121982 for a date field, I get 14/_2/_9822 in the textfield, and 14/_2/_982 internally). Also, this difference between the content of textfield and the content my intenal variable is a issue.
jsfiddle
http://jsfiddle.net/klebermo/f8U4c/41/
code
var counter;
var tam;
var str;
var regex;
$('.valida').each(function(){
$(this).on('focus', function(e){
regex = $(this).attr('pattern');
counter = 0;
tam = size_of(regex);
str = generate_string(regex, tam);
$(this).val(str);
});
$(this).on('keypress', function(e){
var tecla = e.which;
var tecla2 = String.fromCharCode(tecla);
var t = type_of(regex, counter);
if(typeof tecla == t) {
str = replaceAt(str, counter, tecla2);
//counter++;
} else {
if(t != 'number' && t != 'string') {
str = replaceAt(str, counter, t);
counter++;
}
}
counter++;
result = $("<div>");
result.append( "counter = "+counter+"<br>" );
result.append( "tecla2 = "+tecla2+"<br>" );
result.append( "typeof tecla2 = "+typeof tecla+"<br>" );
result.append( "typeof t = "+t+"<br>" );
result.append( "str = "+str+"<br>" );
$("#result").empty().append(result);
$(this).val(str);
});
});
Anyone can see what's wrong here?

After more tryouts, I finally get a working code:
jsfiddle
http://jsfiddle.net/klebermo/f8U4c/78/
code
$('.valida').each(function(){
$(this).on('focus', function(e){
regex = $(this).attr('pattern');
counter = 0;
tam = size_of(regex);
str = generate_string(regex, tam);
$(this).val(str);
});
$(this).on('keypress', function(e){
e.preventDefault();
var tecla = e.which;
if(tecla >= 48 && tecla <= 57)
var tecla2 = tecla - 48;
else
var tecla2 = String.fromCharCode(tecla);
result = $("<div>");
result.append( "tecla = "+tecla+"<br>" );
var t = type_of(regex, counter);
if(counter < tam) {
if(t != 'number' && t != 'string') {
str = replaceAt(str, counter, t);
counter++;
}
t = type_of(regex, counter);
if(typeof tecla2 == t) {
result.append( "tecla2 = "+tecla2+"<br>" );
str = replaceAt(str, counter, tecla2);
counter++;
}
}
result.append( "counter = "+counter+"<br>" );
$("#result").empty().append(result);
$(this).val(str);
});
});

Related

char counter doesn't work with paste event

I have written a code bellow for counting the character inside text box.
the code is working just fine the only problem with it is when i past a text into the text box i have to press any key so system start to count.
Could you please help me sort this problem
function GetAlhpa(text) {
var gsm = "#£$¥èéùìòÇØøÅåΔ_ΦΓΛΩΠΨΣΘΞ^{}\[~]|€ÆæßÉ!\"#¤%&'()*+,-./0123456789:;<=>?¡ABCDEFGHIJKLMNOPQRSTUVWXYZÄÖÑܧ¿abcdefghijklmnopqrstuvwxyzäöñüà";
var i = 0;
while (i <= String(text).length) {
if (gsm.indexOf(String(String(text).charAt(i))) == -1 && (String(text).charCodeAt(i) != 32) && (String(text).charCodeAt(i) != 27) && (String(text).charCodeAt(i) != 10) && (String(text).charCodeAt(i) != 13)) {
UniCodestring = " Unicode ";
Countsms = 70;
if ($('#SndSms_Message').val().length > 70)
Countsms = 67;
return;
}
i++;
}
Countsms = 160;
UniCodestring = "";
if ($('#SndSms_Message').val().length > 160)
Countsms = 153;
}
var Countsms = 160;
var UniCodestring = "";
var CounterSmsLen = 0;
var Two = "|^€{}[]~";
function GetCountSms() {
document.getElementById('SndSms_Message').addEventListener('input', function (e) {
var target = e.SndSms_Message,
position = SndSms_Message.selectionStart;
ConvertGreek();
CounterSmsLen = $('#SndSms_Message').val().length;
GetAlhpa($('#SndSms_Message').val());
var i = 0;
while (i < String(Two).length) {
var oldindex = -1;
while (String($('#SndSms_Message').val()).indexOf(String(String(Two).charAt(i)), oldindex) > -1) {
//if ( String($('#SndSms_Message').val()).indexOf(String(String(Two).charAt(i))) > -1){
CounterSmsLen += 1;
oldindex = String($('#SndSms_Message').val()).indexOf(String(String(Two).charAt(i)), oldindex) + 1;
console.log(i);
}
i++;
}
SndSms_Message.selectionEnd = position; // Set the cursor back to the initial position.
});
if ($('#SndSms_Message').val().length == 0)
CounterSmsLen = 0;
$('#SndSms_Count').html(' ' + CounterSmsLen + ' Characters' + UniCodestring + ' <br /> ' + Math.ceil(CounterSmsLen / Countsms) + ' Sms');
countsmsnumber=Math.ceil(CounterSmsLen / Countsms);
}
var greekchar = "ΑΒΕΖΗΙΚΜΝΟΡΤΥΧ";
var englishchar = "ABEZHIKMNOPTYX";
function ConvertGreek() {
var str = $('#SndSms_Message').val();
var i = 0;
while (i < String(greekchar).length) {
str = str.replace(new RegExp(String(greekchar).charAt(i), 'g'), String(englishchar).charAt(i));
i++;
}
$('#SndSms_Message').val(str);
P.S.
If i paste the number into the text box it will count it correct but if i paste character it wont count them..
You need keyup change event in order to handle paste event.
document.getElementById('SndSms_Message').addEventListener("keyup", function() {
//your code here
});
example

How to insert delimitter on key up after 7 letters/alphabet/numbers and new letters in new line- Jquery

How to put comma after 7 letters on keyup event,Below is my code where I am able to get comma after 7 letters but when it goes to next line it doesn't work properly.
<asp:TextBox ID ="txtbillno" runat="server" onkeyup="InsertComma();" TextMode="MultiLine"></asp:TextBox>
function InsertComma() {
var txtObj = document.getElementById('<%=txtbillno.ClientID %>');
var txtVal = replaceAll(txtObj.value, ',', '');
if (txtObj.value != "") {
var newVal = "";
for (var i = 0; i < txtVal.length; i++) {
newVal = newVal + txtVal.substring(i, i + 1);
if ((i + 1) % 7 == 0 && i != 0) {
newVal = newVal + "," + "\n";
}
}
txtObj.value = newVal;
}
}
function replaceAll(txt, replace, with_this) {
return txt.replace(new RegExp(replace, 'g'), with_this);
}
In your InsertComma function you were correctly removing the commas:
var txtVal = replaceAll(txtObj.value, ',', '');
but txtVal still contains the new line characters (\n), so I added a line to remove those too:
txtVal = replaceAll(txtVal, '\n', '');
The complete InsertComma method is:
function InsertComma() {
var txtObj = document.getElementById('txtbillno');
// Remove commas
var txtVal = replaceAll(txtObj.value, ',', '');
// Remove new line characters
txtVal = replaceAll(txtVal, '\n', '');
if (txtObj.value != "") {
var newVal = "";
// Append commas
for (var i = 0; i < txtVal.length; i++) {
newVal = newVal + txtVal.substring(i, i + 1);
if ((i + 1) % 7 == 0 && i != 0) {
newVal = newVal + "," + "\n";
}
}
txtObj.value = newVal;
}
}
and a working example can be found here

mask work for id but not for class

hi i have a problem with my javascript code it works for input by id but i wat to use it on class element. I do not know what is i am doing wrong any idea? I paste my code
i want to mask time on my input
function maska(inputName, mask, evt) {
var text = document.getElementsByClassName(inputName);
try {
var value = $(text).val(); //text.value;
// Jeśli ktoś naciśnie dela lub backspace to czyszcze inputa
try {
var e = (evt.which) ? evt.which : event.keyCode;
if (e == 46 || e == 8) {
$(text).val() = ""; //text.value = "";
return;
}
} catch (e1) { }
var literalPattern = /[0\*]/;
var numberPattern = /[0-9]/;
var newValue = "";
for (var vId = 0, mId = 0; mId < mask.length; ) {
if (mId >= value.length)
break;
// Wpada jakaś inna wartość niż liczba przechowuje tylko ta dobra wartosc
if (mask[mId] == '0' && value[vId].match(numberPattern) == null) {
break;
}
// Wpadł literał
while (mask[mId].match(literalPattern) == null) {
if (value[vId] == mask[mId])
break;
newValue += mask[mId++];
}
var godzina = value.substr(0, 2);
var minuty = value.substr(3,4);
if (minuty > '59' || godzina > '23') {
break;
}
else
newValue += value[vId++];
mId++;
}
text.val() = newValue;
//text.value = newValue;
} catch (e) { }
}
getElementById returns a single DOMElement while getElementsByClass returns an array of elements. To allow for both, you could have one function that accepts a DOMElement and two functions that find the elements, one for id and one for class:
function maska(elem, mask, evt) {
try {
var value = $(elem).val();
// blah blah, rest of the function
}
function maskById(id, mask, evt) {
var element = document.getElementById(id);
maska(element, mask, evt);
}
function maskByClass(class, mask, evt) {
var element_list = document.getElementsByClass(class);
for(var i = 0; var i < element_list.length; i++) {
maska(element_list[i], mask, evt);
}
}
But you would be better off using the jquery selector combined with .each , which always returns results as a set/array, regardless of selector type.
document.getElementById returns a single element, which your code is written to handle.
document.getElementsByClassName returns multiple elements. You need to loop over them and process them each individually.
I don't get why you use getElementsByClassName and then use jQuery features?
try $('input.' + inputName)
getElementById returns a single element, while getElementsByClassName returns a collection of elements. You need to iterate over this collection
function maska(inputName, mask, evt) {
var text = document.getElementsByClassName(inputName);
try {
for (var i = 0; i < text.length; i++) {
var value = text[i].value;
// Jeśli ktoś naciśnie dela lub backspace to czyszcze inputa
try {
var e = (evt.which) ? evt.which : event.keyCode;
if (e == 46 || e == 8) {
text[i].value = "";
continue;
}
} catch (e1) { }
var literalPattern = /[0\*]/;
var numberPattern = /[0-9]/;
var newValue = "";
for (var vId = 0, mId = 0; mId < mask.length; ) {
if (mId >= value.length)
break;
// Wpada jakaś inna wartość niż liczba przechowuje tylko ta dobra wartosc
if (mask[mId] == '0' && value[vId].match(numberPattern) == null) {
break;
}
// Wpadł literał
while (mask[mId].match(literalPattern) == null) {
if (value[vId] == mask[mId])
break;
newValue += mask[mId++];
}
var godzina = value.substr(0, 2);
var minuty = value.substr(3,4);
if (minuty > '59' || godzina > '23') {
break;
}
else
newValue += value[vId++];
mId++;
}
text[i].value = newValue;
}
} catch (e) { }
}

Jquery clone-able inputs foreach overwrites values

I'm currently creating a clone-able id input field..
the only problem is on submit after validating the id it displays the same values for all duplicates in the console.
what I'm trying to achieve is simply to clone the field make it run through the validation and on submit return the values for each cloned field in JSON.
Any Help greatly appreciated.
Js Fiddle: http://jsfiddle.net/dawidvdh/tBYSA/4/
and then the code:
jQuery -
//Clone Tracking
var g_counter = 1;
var d_counter = 1;
var dependant = ["dependant"];
var group;
//Clone Tracking
//General Variables
var input_groups = ["group-1"];
var idNumber;
var values;
//General Variables
//Generate variables
var id_fields = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 13];
var id_input = "<input class='id' maxlength='1' name='id' type='text' />";
jQuery(document).ready(function(e) {
jQuery(id_fields).each(function() {
jQuery(id_input).appendTo('#group-1');
});
//populate jquery generated fields
//Cloning Function
jQuery('#clone').click(function() {
clone_dependant();
});
function clone_dependant() {
// Store the value of the previous Id to insert the cloned div..
var oldId = g_counter;
g_counter++;
currentdep ='dependant-'+g_counter;
// Clone the Dependant Div and set a new id
var $clonedDiv = jQuery('#dependant-1').clone(false).attr('id', 'dependant-'+g_counter);
var id_newDiv = 'group-'+ g_counter;
// Find div's inside the cloned object and set a new id's
$clonedDiv.find('#group-1').attr('id',"group-" + g_counter );
// You don't need to Loop thru the inputs to set the value
$clonedDiv.find('input[type="text"]').val('');
// Insert the cloned object
$clonedDiv.insertAfter("#dependant-" + oldId);
input_groups.push(id_newDiv);
}
//Cloning Function
//Validation
function validate_Id(values) {
idNumber = values;
var correct = true;
if (idNumber.length != 13 || !isNumber(idNumber)) {correct = false;}
var tempDate = new Date(idNumber.substring(0, 2), idNumber.substring(2, 4) - 1, idNumber.substring(4, 6));
var today = new Date();
var id_date = tempDate.getDate();
var id_month = tempDate.getMonth();
var id_year = tempDate.getFullYear();
var currentYear = (new Date).getFullYear();
var age = Math.floor((today-tempDate) / (365.25 * 24 * 60 * 60 * 1000));
var fullDate = id_date + "-" + (id_month + 1) + "-" + id_year;
if (!((tempDate.getYear() == idNumber.substring(0, 2)) && (id_month == idNumber.substring(2, 4) - 1) && (id_date == idNumber.substring(4, 6)))) {
correct = false;}
var genderCode = idNumber.substring(6, 10);
var gender = parseInt(genderCode) < 5000 ? "Female" : "Male";
var citzenship = parseInt(idNumber.substring(10, 11)) == 0 ? "Yes" : "No";
var tempTotal = 0;
var checkSum = 0;
var multiplier = 1;
for (var i = 0; i < 13; ++i) {tempTotal = parseInt(idNumber.charAt(i)) * multiplier;
if (tempTotal > 9) {tempTotal = parseInt(tempTotal.toString().charAt(0)) + parseInt(tempTotal.toString().charAt(1));}
checkSum = checkSum + tempTotal;
multiplier = (multiplier % 2 == 0) ? 1 : 2;}
if ((checkSum % 10) != 0) {correct = false;};
if (correct) {
$.each(age_input_groups , function(i){
var id = 'age-group-'+g_counter;
var agevalues = $.map($('#'+id + ' input') , function(e,i){
return $(e).val(age);
});
});
$.each(gender_input_groups , function(i){
var id = 'gender-group-'+g_counter;
console.log(gender_input_groups);
var gendervalues = $.map($('#'+id + ' input') , function(e,i){
return $(e).val(gender);
});
});
return idNumber;
}
else {
console.log(idNumber + "-wrong");
}
return false;
}
function isNumber(n) {return !isNaN(parseFloat(n)) && isFinite(n);};
//Validation
//MainID
$(document).on('keydown', 'input.id', function(e) {
if (e.keyCode == 8) {
$(this).val('');
$(this).prev().val('');
$(this).prev().focus();
}
});
$(document).on('keyup', 'input.id', function() {
if (this.value.match(/\d+/)) {
var $this = $(this);
if ($this.next('input.id').length) {
$this.next().focus();
} else {
$.each(input_groups , function(i){
var id = input_groups[i];
values = $.map($('#'+id + ' input') , function(e,i){
return $(e).val();
}).join('');
validate_Id(values);
});
}
}
});
//MainID
$(document).on("click", 'input[type="checkbox"]', function() {
jQuery(this).siblings(":checked").removeAttr('checked');
});
//Multiple Inputs function
//Basic Validation
//Digits only
jQuery(".id").keydown(function(event) {
// Allow: backspace, delete, tab, escape, and enter
if ( event.keyCode == 46 || event.keyCode == 8 || event.keyCode == 9 || event.keyCode == 27 || event.keyCode == 13 ||
// Allow: Ctrl+A
(event.keyCode == 65 && event.ctrlKey === true) ||
// Allow: home, end, left, right
(event.keyCode >= 35 && event.keyCode <= 39)) {
// let it happen, don't do anything
return;
}
else {
// Ensure that it is a number and stop the keypress
if (event.shiftKey || (event.keyCode < 48 || event.keyCode > 57) && (event.keyCode < 96 || event.keyCode > 105 )) {
event.preventDefault();
}
}
});
//Basic Validation
//submit function
var result = {};
var dependants;
var dep_counter = 0;
jQuery('#submit').click(function(){
jQuery('.dependant').each(function(k, v){
dep_counter++
dependants = {};
result['dependant'+dep_counter] = [dependants];
dependants['id'] = idNumber;
});
var jsonData = JSON.stringify(result);
console.log(jsonData);
});
//submit function
});
and then the HTML:
<div id="dependant-1" class="dependant">
<div id="label">id-number:</div> <div id="group-1"></div>
<div id="error_id" class="error"></div>
</div>
<button id="clone">Add a Dependant</button>
<button id="submit">submit</button>
Thanks in advance :).
In function validate_Id, you're using a global variable idNumber, which will be assigned by argument values. So eventually this global variable will be the last validated number.
To solve that, you could change idNumber to an array indexed by corresponding dep_counter.
For example, 3 changes should be enough:
replace var idNumber; with var idNumbers = [];
change validate_Id(values); to:
var idNumber = validate_Id(values);
if (idNumber) {
idNumbers.push(idNumber);
}
change dependants['id'] = idNumber; to dependants['id'] = idNumbers[dep_counter];
BTW, you seem to like global variables, which should be avoided when possible. Even worse, you declared some local variables with the same name of the global ones.
I tried this for you in fiddle..
code:
jQuery('#submit').click(function(){
jQuery('.dependant').each(function(k, v){
dep_counter++
dependants = {};
result['dependant'+dep_counter] = '';
$(v).find(':input').each(function(){
result['dependant'+dep_counter] += $(this).val();
});
//dependants['id'] = idNumber;
});
var jsonData = JSON.stringify(result);
alert(jsonData);
console.log(jsonData);
});

Any Good Number Picker for JQuery (or Javascript)?

Are there any good number picker for jquery (or standalone js)?
I would like a number picker where there is a max and min number that the user can choose from. Also, it have other options such as displaying odd number or even number or prime number or a range of number whereby some numbers in between are skipped.
Using a select to do this you can create an array with the numbers to skip and do a for loop to write the options:
int minNumber = 0;
int maxNumber = 10;
int[] skipThese = { 5, 7 };
for (int i = minNumber; i <= maxNumber; i++)
{
if(!skipThese.Contains(i)) Response.Write(String.Concat("<option value=\"", i, "\">", i, "</option>"));
}
You can do this with razor or any other way to output the HTML.
You can also do this with jQuery, dynamicaly, following the same idea:
$(document).ready(function() {
var minNumber = 0;
var maxNumber = 10;
var skipThese = [5, 7];
for (var i = minNumber; i <= maxNumber; i++) {
if ($.inArray(i, skipThese) == -1) $('#selectListID').append("<option value=\"" + i + "\">" + i + "</option>");
}
});
Edit:
Or you can use the C# code above in an aspx page and load it with AJAX from the page:
Create a select box in the page:
<select name="numPicker" id="numPicker">
<option>Loading...</option>
</select>
In a script in this page you could use jQuery's ajax() to fetch the data and populate the <select>:
$(document).ready(function() {
var numPickerSelect = $("#numPicker");
$.ajax({
url: 'url/to/page.aspx',
type: 'post'
success: function(data) {
numPickerSelect.find('option').remove(); // Remove the options in the select field
numPickerSelect.append(data); // Load the content generated by the server into the select field
},
error: function() {
alert('An error has ocurred!');
}
});
//Or use this (not sure if will work)
numPickerSelect.load("url/to/page.aspx");
});
I have used this. You should be able to modify to add extra options such as min and max fairly easily.
// Make a control only accept numeric input
// eg, $("#myedit").numeric()
// $("#myedit").numeric({alow: ' ,.'})
// $("#myedit").numeric({decimals: 2})
(function($) {
$.fn.alphanumeric = function(p) {
if (p == 'destroy') {
$(this).unbind('keypress');
$(this).unbind('blur');
return;
}
p = $.extend({
ichars: "!##$%^&*()+=[]\\\';,/{}|\":<>?~`.- ",
nchars: "",
allow: "",
decimals: null
}, p);
return this.each
(
function() {
if (p.nocaps) p.nchars += "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
if (p.allcaps) p.nchars += "abcdefghijklmnopqrstuvwxyz";
s = p.allow.split('');
for (i = 0; i < s.length; i++) if (p.ichars.indexOf(s[i]) != -1) s[i] = "\\" + s[i];
p.allow = s.join('|');
var reg = new RegExp(p.allow, 'gi');
var ch = p.ichars + p.nchars;
ch = ch.replace(reg, '');
var dp = p.decimals;
var isInteger = function(val) {
var objRegExp = /(^-?\d\d*$)/;
return objRegExp.test(val);
};
var isNumeric = function(val) {
// If the last digit is a . then add a 0 before testing so if they type 25. it will be accepted
var lastChar = val.substring(val.length - 1);
if (lastChar == ".") val = val + "0";
var objRegExp = new RegExp("^\\s*-?(\\d+(\\.\\d{1," + dp + "})?|\\.\\d{1," + dp + "})\\s*$", "g");
if (dp == -1)
objRegExp = new RegExp("^\\s*-?(\\d+(\\.\\d{1,25})?|\\.\\d{1,25})\\s*$", "g");
var result = objRegExp.test(val);
return result;
};
$(this).blur(function(e) {
var text = $(this).val();
if (dp != null) {
if (dp == 0) {
if (!isInteger(text)) {
$(this).val('');
e.preventDefault();
}
}
else {
if (!isNumeric(text)) {
$(this).val('');
e.preventDefault();
}
}
} else {
var c = text.split('')
for (i = 0; i < text.length; i++) {
if (ch.indexOf(c[i]) != -1) {
$(this).val('');
e.preventDefault();
};
}
}
});
$(this).keypress
(
function(e) {
switch (e.which) {
//Firefox fix, for ignoring specific presses
case 8: // backspace key
return true;
case 46: // delete key
return true;
};
if (dp != null) {
if (e.which == 32) { e.preventDefault(); return false; }
var range = getRange(this);
var typed = String.fromCharCode(e.which);
var text = $(this).val().substr(0, range.start) + typed + $(this).val().substr(range.start);
if (dp == 0) {
if (!isInteger(text)) e.preventDefault();
}
else {
if (!isNumeric(text)) e.preventDefault();
}
return;
}
if (!e.charCode) k = String.fromCharCode(e.which);
else k = String.fromCharCode(e.charCode);
if (ch.indexOf(k) != -1) e.preventDefault();
if (e.ctrlKey && k == 'v') e.preventDefault();
}
);
$(this).bind('contextmenu', function() { return false });
}
);
};
$.fn.numeric = function(p) {
if (p == 'destroy') {
$(this).unbind('keypress');
$(this).unbind('blur');
return;
}
var az = "abcdefghijklmnopqrstuvwxyz";
az += az.toUpperCase();
var opts = {};
if (!isNaN(p)) {
opts = $.extend({
nchars: az
}, { decimals: p });
} else {
opts = $.extend({
nchars: az
}, p);
}
return this.each(function() {
$(this).alphanumeric(opts);
}
);
};
$.fn.integer = function(p) {
if (p == 'destroy') {
$(this).unbind('keypress');
$(this).unbind('blur');
return;
}
var az = "abcdefghijklmnopqrstuvwxyz";
az += az.toUpperCase();
p = {
nchars: az,
allow: '-',
decimals: 0
};
return this.each(function() {
$(this).alphanumeric(p);
}
);
};
$.fn.alpha = function(p) {
if (p == 'destroy') {
$(this).unbind('keypress');
$(this).unbind('blur');
return;
}
var nm = "1234567890";
p = $.extend({
nchars: nm
}, p);
return this.each(function() {
$(this).alphanumeric(p);
}
);
};
})(jQuery);

Categories

Resources