Jquery clone-able inputs foreach overwrites values - javascript

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

Related

Synchronous input update with selected digit in HTML/JavaScript

I'm trying to implement a customised input that can use left or right arrow key to select the digit and use up/down arrow key to increment/decrement the digit. Here's the code in jsfiddle: http://jsfiddle.net/uk5t3z4d/48/. However, I have two problems:
I cannot add digit using the number pad, the input always stays at X.XX
When I use another function I wrote (parseLocalFloat which is commented out), the output stops displaying anything, and I cannot use the left and right key to select the digit etc.
How can I overcome these two issues? Please shed a light on me, thanks!
HTML
<div class="display" id="out"></div>
<div class="form-group">
<label for="comment">value:</label>
<input class="form-control" type="text" value="0.00" id="in"></input>
</div>
JavaScript
function createSelection(field, start, end) {
if( field.createTextRange ) {
var selRange = field.createTextRange();
selRange.collapse(true);
selRange.moveStart('character', start);
selRange.moveEnd('character', end);
selRange.select();
} else if( field.setSelectionRange ) {
field.setSelectionRange(start, end);
} else if( field.selectionStart ) {
field.selectionStart = start;
field.selectionEnd = end;
}
}
function getLocalDecimalSeparator() {
var n = 1.1;
return n.toLocaleString().substring(1,2);
}
function parseLocalFloat(num) {
return +(num.replace(getLocalDecimalSeparator(), '.'));
}
var inputBox = document.getElementById('in');
//var inputBox = parseLocalFloat(document.getElementByID('in').value);
inputBox.onkeyup = function(){
document.getElementById('out').innerHTML = inputBox.value;
}
$('#in').on("keydown", function(e){
var gotCode = false;
var curPos = this.selectionStart;
var endPos = this.selectionEnd;
if(curPos !== endPos) {
createSelection(this, curPos, curPos+1);
}
// get the position
if(e.keyCode == 37){
curPos--;
gotCode=true;
}
if(e.keyCode == 39){
curPos++;
gotCode=true;
}
var before = $(this).val().substring(0,curPos);
var after = $(this).val().substring(curPos+1);
var cur = Number($(this).val().substring(curPos, curPos+1));
// avoid adding extra stuff
if(curPos < $(this).val().length) {
if(e.keyCode == 38) {
cur++;
if(cur > 9) cur = 0;
$(this).val(before + '' + cur + '' + after);
gotCode=true;
}
if(e.keyCode == 40) {
cur--;
if(cur < 0) cur = 9;
$(this).val(before + '' + cur + '' + after);
gotCode=true;
}
}
if(!gotCode) {
e.preventDefault();
return false;
}
var field = this;
window.setTimeout(function(){
createSelection(field, curPos, curPos+1);
}, 10);
});
as for the "get number keys to work":
as stated you need to add the keys you want to support:
if(e.keyCode >= 48 && e.keyCode <= 57) {
var num = e.keyCode - 48; // 0=48; 9=59
$(this).val(before + '' + num + '' + after);
gotCode = true;
e.preventDefault(); // otherwise a new number is added as well
}
(this needs to come before the if (!gotCode) ... )
as for the customFloat: the the response from Moishe
For #1:
if(!gotCode) {
e.preventDefault();
return false;
}
ensures that if gotCode is false the default event (which in this case is the default keydown event) will not occur.
gotCode only seems to be true if keyCode is equal to 37, 38, 39, or 40 (the arrow keys). You are essentially preventing the other keys (like number keys) from having any effect on the textBox.
You probably would like to enable the number keys (when shift or caps aren't on) and number pad keys.
Additionally, you may want to check that the cur is a number (and not .) before attempting to increment or decrement its value.
You could do:
var isNumberKey = (
( e.keyCode >= 48 //is more than or equal to 0 key
&& e.keyCode <= 57 //is less than or equal to 9 key
&& !e.shiftKey) //shift key or cap key not on
|| ( e.keyCode >= 96 //more than or equal to 0 key in number pad
&& e.keyCode <= 105)); //less than or equal to 9 key in number pad
if(!gotCode && !isNumberKey) { //not arrow key or number key
console.log(e);
e.preventDefault();
return false;
}
For #2:
var inputBox = parseLocalFloat(document.getElementByID('in').value);
is setting inputBox to whatever parseLocalFloat returns which happens to be a number.
This is problematic because you then attempt to attach a keyUp event to that number instead of the inputBox:
inputBox.onkeyup = function(){
document.getElementById('out').innerHTML = inputBox.value;
}
You may want to instead call parseLocalFloat on the number and set the out textBox's value to that:
var inputBox = document.getElementById('in');
inputBox.onkeyup = function(){
document.getElementById('out').innerHTML = parseLocalFloat(inputBox.value);
}
function createSelection(field, start, end) {
if( field.createTextRange ) {
var selRange = field.createTextRange();
selRange.collapse(true);
selRange.moveStart('character', start);
selRange.moveEnd('character', end);
selRange.select();
} else if( field.setSelectionRange ) {
field.setSelectionRange(start, end);
} else if( field.selectionStart ) {
field.selectionStart = start;
field.selectionEnd = end;
}
}
function getLocalDecimalSeparator() {
var n = 1.1;
return n.toLocaleString().substring(1,2);
}
function parseLocalFloat(num) {
return +(num.replace(getLocalDecimalSeparator(), '.'));
}
var inputBox = document.getElementById('in');
// var inputBox = parseLocalFloat(document.getElementByID('in').value);
inputBox.onkeyup = function(){
document.getElementById('out').innerHTML = parseLocalFloat(inputBox.value);
}
$('#in').on("keydown", function(e){
var gotCode = false;
var curPos = this.selectionStart;
var endPos = this.selectionEnd;
if(curPos !== endPos) {
createSelection(this, curPos, curPos+1);
}
// get the position
if(e.keyCode == 37){
curPos--;
gotCode=true;
}
if(e.keyCode == 39){
curPos++;
gotCode=true;
}
var $thisVal = $(this).val();
var before = $thisVal.substring(0,curPos);
var after = $thisVal.substring(curPos+1);
var cur = Number($thisVal.substring(curPos, curPos+1));
// avoid adding extra stuff
if(curPos < $thisVal.length && !isNaN(cur)) {
if(e.keyCode == 38) {
cur++;
if(cur > 9) cur = 0;
$(this).val(before + '' + cur + '' + after);
gotCode=true;
}
if(e.keyCode == 40) {
cur--;
if(cur < 0) cur = 9;
$(this).val(before + '' + cur + '' + after);
gotCode=true;
}
}
var isNumberKey = ((e.keyCode >= 48 && e.keyCode <= 57 && [16, 20].indexOf(e.keyCode) == -1 && !e.shiftKey) || (e.keyCode >= 96 && e.keyCode <= 105));
if(!gotCode && !isNumberKey) {
console.log(e);
e.preventDefault();
return false;
}
var field = this;
window.setTimeout(function(){
createSelection(field, curPos, curPos+1);
}, 10);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="display" id="out"></div>
<div class="form-group">
<label for="comment">value:</label>
<input class="form-control" type="text" value="0.00" id="in"></input>
</div>

validation script losing characters

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

duplicate-able inputs validation not working with non duplicate-able fields

I'm in the process of creating a duplicate-able form, i have run into a slight problem though.
i have a main-member inputs and a duplicate-able dependent inputs that gets run through an id validation, that automatically gives you age and sex based on your id.
and my problem is, all the duplicates get unique ages and sex's based on there id but the main member gets the sex of the first dependent.
The code has to stay in the same format as it is now to work with the rest of the code.
heres a jsFiddle: http://jsfiddle.net/dawidvdh/ZQwZm/
example of an id: 85 0929 5266086
and the code:
jQuery:
// JavaScript Document
//Clone Tracking
var g_counter = 1;
var d_counter = 1;
var dependant = ["dependant"];
var group;
//Clone Tracking
//Main Variables
var main_input_groups = ["main_group-1"];
var main_age_input_groups = ["main_age_group-1"];
var main_gender_input_groups = ["main_gender_group-1"];
//Main Variables
//General Variables
var input_groups = ["group-1"];
var age_input_groups = ["age-group-1"];
var gender_input_groups = ["gender-group-1"];
var idNumber;
var cell_values;
var pass_values;
var values;
//General Variables
//Generate variables
var id_fields = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 13];
var age_fields=[0,1];
var gender_fields=[0];
//Main Member generate
var main_id_fields = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 13];
var main_age_fields = [0,1];
var main_gender_fields = [0];
//Main Member generate
//Main Member inputs
var mainID;
var mainPAS;
var mainCon;
var mainCod;
//Main Member inputs
//Main Member gen
var main_id_input = "<input class='mainid' maxlength='1' name='mainid' type='text' />";
var main_age_input = "<input class='mainage' maxlength='1' name='mainage' type='text' />";
var main_gender_input = "<input class='maingender' maxlength='1 name='maingender' type='text' />";
//Main Member gen
var id_input = "<input class='id' maxlength='1' name='id' type='text' />";
var age_input = "<input class='age' name='age' type='text' />";
var gender_input = "<input class='gender' maxlength='1' name='gender' type='text' />";
//Generate variables
jQuery(document).ready(function(e) {
//Member
jQuery(main_id_fields).each(function() {
jQuery(main_id_input).appendTo('#main_group-1');
});
jQuery(main_age_fields).each(function() {
jQuery(main_age_input).appendTo('#main_age_group-1');
});
jQuery(main_gender_fields).each(function() {
jQuery(main_gender_input).appendTo('#main_gender_group-1');
});
//Member
//populate jquery generated fields
jQuery(id_fields).each(function() {
jQuery(id_input).appendTo('#group-1');
});
jQuery(age_fields).each(function() {
jQuery(age_input).appendTo('#age-group-1');
});
jQuery(gender_fields).each(function() {
jQuery(gender_input).appendTo('#gender-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 gender_newDiv = 'gender-group-'+ g_counter;
var age_newDiv = 'age-group-'+ 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 );
$clonedDiv.find('#age-group-1').attr('id',"age-group-" + g_counter );
$clonedDiv.find('#gender-group-1').attr('id',"gender-group-" + g_counter );
// You don't need to Loop thru the inputs to set the value
$clonedDiv.find('input:checkbox').removeAttr('checked');
$clonedDiv.find('input[type="text"]').val('');
// Insert the cloned object
$clonedDiv.insertAfter("#dependant-" + oldId);
age_input_groups.push(age_newDiv);
gender_input_groups.push(gender_newDiv);
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){
$('#'+id + ' input').first().val(Math.floor(age / 10));
$('#'+id + ' input').last().val(age % 10);
//return $(e).val(age);
});
});
$.each(gender_input_groups , function(i){
var id = 'gender-group-'+g_counter;
var gendervalues = $.map($('#'+id + ' input') , function(e,i){
return $(e).val(gender);
});
});
$.each(main_gender_input_groups , function(i){
var id = 'main_gender_group-'+g_counter;
var maingendervalues = $.map($('#'+id + ' input') , function(e,i){
return $(e).val(gender);
});
});
$.each(main_age_input_groups , function(i){
var id = 'main_age_group-'+g_counter;
var mainagevalues = $.map($('#'+id + ' input') , function(e,i){
$('#'+id + ' input').first().val(Math.floor(age / 10));
$('#'+id + ' input').last().val(age % 10);
})
});
return idNumber;
}
else {
console.log(idNumber + "-wrong");
}
return false;
}
function isNumber(n) {return !isNaN(parseFloat(n)) && isFinite(n);};
//Validation
//Multiple Inputs function
//ID
$(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);
});
}
}
});
//ID
//MainID
$(document).on('keydown', 'input.mainid', function(e) {
if (e.keyCode == 8) {
$(this).val('');
$(this).prev().val('');
$(this).prev().focus();
}
});
$(document).on('keyup', 'input.mainid', function() {
if (this.value.match(/\d+/)) {
var $this = $(this);
if ($this.next('input.mainid').length) {
$this.next().focus();
} else {
$.each(main_input_groups , function(i){
var id = main_input_groups[i];
values = $.map($('#'+id + ' input') , function(e,i){
return $(e).val();
}).join('');
validate_Id(values);
});
}
}
});
//MainID
//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();
}
}
});
//Digits only
$('.error').hide();
//Basic Validation
//submit function
var result = {};
var dependants;
var mainmember;
var dep_counter = 0;
jQuery('#submit').click(function(){
jQuery('.main-member').each(function(k, v){
mainmember = {}
result['mainmember'] = [mainmember];
mainmember['id'] = '';
$(v).find('.mainid').each(function(){mainmember['id'] += $(this).val();});
mainmember['age'] = '';
$(v).find('.mainage').each(function(){
mainmember['age'] += $(this).val();
});
mainmember['gender'] = $(v).find('.main_gender').val();
});
jQuery('.dependant').each(function(k, v){
var dep_id = idNumber;
var iden_values;
dep_counter++
dependants = {};
result['dependant'+dep_counter] = [dependants];
dependants['id'] = '';
$(v).find('.id').each(function(){
dependants['id'] += $(this).val();
});
dependants['age'] = '';
$(v).find('.age').each(function(){
dependants['age'] += $(this).val();
});
dependants['gender'] = $(v).find('.gender').val();
});
var jsonData = JSON.stringify(result);
console.log(jsonData);
jQuery.ajax({
type: "POST",
url: "mail.php",
dataType: "json",
data: {parameters: jsonData}
});
});
//submit function
});
and the HTML:
<div id="app_wrap">
<div class="main-member">
<div class="block_wrap left border_right">
<div class="block">main id-number:<div id="main_group-1" class="right"></div></div>
<div class="block_half left border_right">age:<div id="main_age_group-1" class="right"></div></div>
<div class="block_half right">gender:<div id="main_gender_group-1" class="right"></div></div>
</div>
</div>
<div id="dependant-1" class="dependant">
<div id="dependant">
<div class="block_wrap left border_right">
<div class="block">duplicate id-number:<div id="group-1" class="right"></div></div>
<div class="block_half left border_right">age:<div id="age-group-1" class="right"></div></div>
<div class="block_half right">gender: <div id="gender-group-1" class="right"></div></div>
</div>
</div>
</div>
<button id="clone">Add a Dependant</button>
<button id="submit">submit</button>
</div>
if any further explanation is needed feel free to ask.
Thanks, any and all help is greatly appreciated.
Here is how can be solved http://jsfiddle.net/mgechev/ZQwZm/12/
I simplified the code a lot but you need to refactor it to became more readable.
Here is the JavaScript:
// JavaScript Document
//Clone Tracking
var g_counter = 1;
var d_counter = 1;
var dependant = ["dependant"];
var group;
//Clone Tracking
//Main Variables
var main_input_groups = ["group-1"];
var main_age_input_groups = ["age_group-1"];
var main_gender_input_groups = ["gender_group-1"];
//Main Variables
//General Variables
var input_groups = ["group-2"];
var age_input_groups = ["age-group-2"];
var gender_input_groups = ["gender-group-2"];
var idNumber;
var cell_values;
var pass_values;
var values;
//General Variables
//Generate variables
var id_fields = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 13];
var age_fields=[0,1];
var gender_fields=[0];
//Main Member generate
var main_id_fields = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 13];
var main_age_fields = [0,1];
var main_gender_fields = [0];
//Main Member generate
//Main Member inputs
var mainID;
var mainPAS;
var mainCon;
var mainCod;
//Main Member inputs
//Main Member gen
var main_id_input = "<input class='id' maxlength='1' name='id' type='text' />";
var main_age_input = "<input class='age' name='age' type='text' />";
var main_gender_input = "<input class='gender' maxlength='1' name='gender' type='text' />";
//Generate variables
jQuery(document).ready(function(e) {
//Member
jQuery(main_id_fields).each(function() {
jQuery(main_id_input).appendTo('#group-1');
});
jQuery(main_age_fields).each(function() {
jQuery(main_age_input).appendTo('#age_group-1');
});
jQuery(main_gender_fields).each(function() {
jQuery(main_gender_input).appendTo('#gender_group-1');
});
//Member
//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', currentdep);
var gender_newDiv = 'gender-group-'+ g_counter;
var age_newDiv = 'age-group-'+ 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 );
$clonedDiv.find('#age-group-1').attr('id',"age-group-" + g_counter );
$clonedDiv.find('#gender-group-1').attr('id',"gender-group-" + g_counter );
// You don't need to Loop thru the inputs to set the value
$clonedDiv.find('input:checkbox').removeAttr('checked');
$clonedDiv.find('input[type="text"]').val('');
// Insert the cloned object
$clonedDiv.insertAfter("#dependant-" + oldId);
age_input_groups.push(age_newDiv);
gender_input_groups.push(gender_newDiv);
input_groups.push(id_newDiv);
}
//Cloning Function
//Validation
function validate_Id(values, p) {
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) {
var aig = p.find('.age');
aig.first().val(Math.floor(age / 10));
aig.last().val(age % 10);
p.find('.gender').val(gender);
/*
$.each(main_gender_input_groups , function(i){
var id = 'main_gender_group-'+g_counter;
var maingendervalues = $.map($('#'+id + ' input') , function(e,i){
return $(e).val(gender);
});
});
$.each(main_age_input_groups , function(i){
var id = 'main_age_group-'+g_counter;
var mainagevalues = $.map($('#'+id + ' input') , function(e,i){
$('#'+id + ' input').first().val(Math.floor(age / 10));
$('#'+id + ' input').last().val(age % 10);
})
});*/
return idNumber;
}
else {
console.log(idNumber + "-wrong");
}
return false;
}
clone_dependant();
function isNumber(n) {return !isNaN(parseFloat(n)) && isFinite(n);};
//Validation
//Multiple Inputs function
//ID
$(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 {
var input_groups = $this.parent();
console.log(input_groups);
$.each(input_groups , function(i){
var inpg = input_groups[i];
values = $.map($(inpg).children('input'), function(e,i){
return $(e).val();
}).join('');
validate_Id(values, input_groups.parent().parent());
});
}
}
});
//ID
//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 {
var main_input_groups = $this.parent();
$.each(main_input_groups , function(i, el){
values = $.map($(el).children('input'), function(e,i){
return $(e).val();
}).join('');
validate_Id(values, main_input_groups.parent().parent().parent());
});
}
}
});
//MainID
//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();
}
}
});
//Digits only
$('.error').hide();
//Basic Validation
//submit function
var result = {};
var dependants;
var mainmember;
var dep_counter = 0;
jQuery('#submit').click(function(){
jQuery('div[class*="dependant"]').each(function(k, v){
var dep_id = idNumber;
var iden_values;
dep_counter++
dependants = {};
result['dependant'+k] = [dependants];
dependants['id'] = '';
$(v).find('.id').each(function(){
dependants['id'] += $(this).val();
});
dependants['age'] = '';
$(v).find('.age').each(function(){
dependants['age'] += $(this).val();
});
dependants['gender'] = $(v).find('.gender').val();
});
var jsonData = JSON.stringify(result);
console.log(jsonData);
jQuery.ajax({
type: "POST",
url: "mail.php",
dataType: "json",
data: {parameters: jsonData}
});
});
//submit function
});

How to make this validation work on cloned inputs

I have this id validation field, i just need to know how i can make the validation and the keydown and keyup functions work on cloned inputs. also inserted data is carrying over to the duplicate fields.
js fiddle- http://www.jsfiddle.net/dawidvdh/xRh9v/
Heres the js:
$(document).ready(function() {
idAmount = [0,1,2,3,4,5,6,7,8,9,10,12,13];
var idinc =1;
var id_val;
jQuery(idAmount).each(function() {
var index = "id"+idinc++;
var id_input = "<input class='id' id="+'"'+index+'"'+" "+" maxlength='1' />";
id_val = $(this).attr('value');
jQuery(id_input).appendTo('#id');
});
$("#clone").click(function () {
var clonedObj=$('#id').clone().insertAfter("#id");
clonedObj.find('.id').each(function(){
this.id='id' + idinc++;
});
});
function Validate() {
jQuery('#error p').remove();
var id_val = '';
$('.id').each(function(){ id_val+=($(this).val());});
var idNumber = id_val;
console.log(id_val);
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));
console.log(tempDate);
var id_date = tempDate.getDate();
var id_month = tempDate.getMonth();
var id_year = tempDate.getFullYear();
var currentYear = (new Date).getFullYear();
var age = currentYear - id_year;
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;
}
// get the gender
var genderCode = idNumber.substring(6, 10);
var gender = parseInt(genderCode) < 5000 ? "Female" : "Male";
// get country ID for citzenship
var citzenship = parseInt(idNumber.substring(10, 11)) == 0 ? "Yes" : "No";
// apply Luhn formula for check-digits
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 no error found, hide the error message
if (correct) {
jQuery('.id').css("border","1px solid #9A8B7D");
// clear the result div
jQuery('#result').empty();
// and put together a result message
jQuery('#result').append('<p>South African ID Number: ' + idNumber + '</p><p>Birth Date: ' + fullDate + '</p><p>Gender: ' + gender + '</p><p>SA Citizen: ' + citzenship + '</p><p>AGE: ' + age + '</p>');
jQuery('#status').html("correct");
}
// otherwise, show the error
else {
jQuery('.id').css("border","1px solid #FF0000");
jQuery('#status').html("incorrect")
}
return false;
}
function isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
$('input.id').keydown(function(e){
if(e.keyCode == 8){
$(this).val('');
$(this).prev().val('');
$(this).prev().focus();
Validate()
}
});
$('input.id').on('keyup', function(){
if (this.value.match(/\d+/)) {
var $this = $(this);
if ($this.next('input').length) {
$this.next().focus();
} else {
Validate()
}
}
});
$(".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();
}
}
});
});
HTML:
<div id="id">
<span id="label">ID NUMBER:</span>
<span id="status"></span>
</div>
<button id="clone">clone</button>
<div id="result"> </div>
CSS:
#error {
color: red;
border: 1px solid red;
padding: 5px;
display: none;
}
#result {
padding: 20px;
}
.id {
width:16px;
height:16px;
border:1px solid #9A8B7D;
margin:0;
float:left;
text-align:center;
font-family:'itc_avant_garde_gothic_bookOb',Helvetica,sans-serif;
font-size:11pt;
padding:2px;
}
#label {
float:left;
font-family:'itc_avant_garde_gothic_bookOb',Helvetica,sans-serif;
line-height:18px;
font-size:11pt;
margin-right:10px;
}
The only time that I see you call Validate is here :
$('input.id').on('keyup', function(){
//code
});
and here
$('input.id').keydown(function(e){
//code
});
Which means that the issue is the event handler is not delegated to a static element
$(document).on('keyup', 'input.id', function(){
//code
});
$(document).on('keydown', 'input.id', function(){
//code
});
Binding it to the document will ensure that any dynamically created elements will have the same event delegated to them as any static elements of the same selector.
Forgot the last part.
clonedObj.find('.id').each(function(){
this.id='id' + idinc++;
this.value = ''; //simply add this to remove the value
});
Although, because you're using jQuery, you should try to stick to using jQuery.
clonedObj.find('.id').each(function(){
$(this).prop('id', 'id'+ idinc++).val(''); // chain the commands
});

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