If x equals something then do not run function - javascript

I am new to JavaScript and HTML. I have this line of code in my JavaScript file:
if (q1 == '' && q2 == '' && q3 == '' && q4 == '' && q5 == '') {alert("You must enter a question");thisform.q1.focus();return false;}
Basically, q1 q2 and so on are textboxes and if they are left blank an alert pops up and says You must enter a question. In my HTML file I have this line of code
<script type="text/javascript">
function add() {
var num = document.getElementById("n1").value;
if(num == '') num = 0;
document.getElementById("n1").value = parseInt(num ,10) + 1;
var num = document.getElementById("n2").value;
if(num == '') num = 0;
document.getElementById("n2").value = parseInt(num ,10) + 1;
var num = document.getElementById("n3").value;
if(num == '') num = 0;
document.getElementById("n3").value = parseInt(num ,10) + 1;
var num = document.getElementById("n4").value;
if(num == '') num = 0;
document.getElementById("n4").value = parseInt(num ,10) + 1;
var num = document.getElementById("n5").value;
if(num == '') num = 0;
document.getElementById("n5").value = parseInt(num ,10) + 1;
}
</script>
Then Later:
<INPUT onclick="addQ(myForm);add();" value="Add Question" id="question add" type=button>
Is there any way that I can make the add() function not execute if my alert pops up?

You can try
<INPUT onclick="if(!addQ(myForm)) {return false;} add();" value="Add Question" id="question add" type=button>
then add a return true; to the end of function addQ().
function addQ(myForm){
....
if (q1 == '' && q2 == '' && q3 == '' && q4 == '' && q5 == '') {alert("You must enter a question");thisform.q1.focus();return false;}
......
.....
return true;
}
or
<INPUT onclick="if(addQ(myForm) === false) {return false;} add();" value="Add Question" id="question add" type=button>

Related

How do you keep the previous text you have had and add new text after it?(without erasing the script)

How do you keep the previous text you have had and add new text after it? (using this script)
it's hard for me to figure out how it will combine values.
if i type "hello" it will show only the last letter you typed how can you make it so it will say "hello" when you type hello.
<!DOCTYPE html>
<html>
<head>
<script>
document.addEventListener('keydown', (event) => {
var name = event.key;
var code = event.code;
if (name == "q"){
var num = "q";
}if (name == "w"){
var num = "w";
}if (name == "e"){
var num = "e";
}if (name == "r"){
var num = "r";
}if (name == "t"){
var num = "t";
}if (name == "y"){
var num = "y";
}if (name == "u"){
var num = "u";
}if (name == "i"){
var num = "i";
}if (name == "o"){
var num = "o";
}
if (name == "p"){
var num = "p";
}
if (name == "a"){
var num = "a";
}if (name == "s"){
var num = "s";
}if (name == "d"){
var num = "d";
}if (name == "f"){
var num = "f";
}if (name == "g"){
var num = "g";
}if (name == "h"){
var num = "h";
}if (name == "j"){
var num = "j";
}if (name == "k"){
var num = "k";
}if (name == "l"){
var num = "l";
}if (name == "z"){
var num = "z";
}if (name == "x"){
var num = "x";
}if (name == "c"){
var num = "c";
}if (name == "v"){
var num = "v";
}if (name == "b"){
var num = "b";
}if (name == "n"){
var num = "n";
}if (name == "m"){
var num = "m";
}if (name == "1"){
var num = 1;
}if (name == "2"){
var num = 2;
}if (name == "3"){
var num = 3;
}if (name == "4"){
var num = 4;
}if (name == "5"){
var num = 5;
}if (name == "6"){
var num = 6;
}if (name == "7"){
var num = 7;
}if (name == "8"){
var num = 8;
}if (name == "9"){
var num = 9;
}if (name == "0"){
var num = 0;
}if (name == "."){
var num = ".";
}if (name == "!"){
var num = "!";
}if (name == "#"){
var num = "#";
}if (name == "("){
var num = "(";
}if (name == ")"){
var num = ")";
}if (name == " "){
var num = " ";
}if (name == "?"){
var num = "?";
}if (name == ","){
var num = ",";
}
if (num!=NaN){
if (num!=undefined){
document.getElementById("test").innerHTML=num;
}
}
}, false);
</script>
</head><body>
<p id="test">No value</p>
</body>
</html>
I want it to add n to previous values

JavaScript While Loop Variable Returning NaN

I'm making a Numerology conversion web app with JavaScript and HTML5. I've ran into a strange issue with a variable and loops. Below is my whole project in its current form.
<html>
<body>
<h1>My First Numerology Project</h1>
<form>
Month:<br>
<input type="text" maxlength="2" name="userInputMonth" id='userInputMonth'>
<br>
Day:<br>
<input type="text" maxlength="2" name="userInputDay" id='userInputDay'>
<br>
Year:<br>
<input type="text" maxlength="4" name="userInputYear" id='userInputYear'>
<br><br>
First Name:<br>
<input type="text" name="userInputFirstName" id='userInputFirstName'>
<br>
Middle Name:<br>
<input type="text" name="userInputMiddleName" id='userInputMiddleName'>
<br>
Last Name:<br>
<input type="text" name="userInputLastName" id='userInputLastName'>
<br><br>
<input type="button" value="Calculate" name="Calculate" onclick="BirthDayCalculation()"/>
</form>
<p id="LLNResult"></p>
<br>
<p id="OPNResult"></p>
<br>
<p id="SNResult"></p>
<br>
<p id="PODNResult"></p>
<script type="text/javascript">
//Defined var
var LLNTemp1;
var LLNTemp2;
var LLNReduce1;
var LLNReduce2;
var NameTemp1;
var NameTemp2;
var OPNReduce1;
var OPNReduce2;
var SNReduce1;
var SNReduce2;
var PODNReduce1;
var PODNReduce2;
function BirthDayCalculation() {
var Reduction1 = 0;
var LLNReduceFinal2 = 0;
var Day = document.getElementById('userInputDay').value;
var Month = document.getElementById('userInputMonth').value;
var Year = document.getElementById('userInputYear').value;
var FirstName = document.getElementById('userInputFirstName').value;
var MiddleName = document.getElementById('userInputMiddleName').value;
var LastName = document.getElementById('userInputLastName').value;
var LLN = ("" + Day + Month + Year).toString();
var FullName = ("" + FirstName + MiddleName + LastName).toString().toUpperCase();
var FullNameLength = parseInt(FullName.length);
var LLNLength = parseInt(("" + Day + Month + Year).length);
var i = 0;
var LLNTemp2 = 0;
while (i < LLNLength) {
LLNTemp1 = parseInt(LLN.charAt(i));
LLNTemp2 += LLNTemp1;
i++;
}
if (LLNTemp2 > 9) {
var i = 0;
var a = parseInt(LLNTemp2.toString().length);
var LLNReduceFinal1 = 0;
var LLNTemp3String = LLNTemp2.toString();
while (i < a) {
LLNReduce1 = parseInt(LLNTemp3String.charAt(i));
LLNReduceFinal1 += LLNReduce1;
i++;
}
var LLNReduceFinal2 = 0;
var Reduction1 = LLNReduceFinal1;
if (LLNReduceFinal1 > 9) {
var i = 0;
var a = parseInt(Reduction1.toString().length);
var LLNTemp3String = Reduction1.toString();
while (i < a) {
LLNReduce1 = parseInt(LLNTemp3String.charAt(i));
LLNReduceFinal2 += LLNReduce1;
i++;
}
}
}
var OPN = 0;
var SN = 0;
var PODN = 0;
var PODNWhole = 0;
var i = 0;
while (i < FullNameLength) {
NameTemp1 = FullName.charAt(i);
var OPNTemp = 0;
var SNTemp = 0;
if (NameTemp1 == "A") SNTemp = 1;
if (NameTemp1 == "J" || NameTemp1 == "S") OPNTemp = 1;
if (NameTemp1 == "B" || NameTemp1 == "K" || NameTemp1 == "T") OPNTemp = 2;
if (NameTemp1 == "C" || NameTemp1 == "L") OPNTemp = 3;
if (NameTemp1 == "U") SNTemp = 3;
if (NameTemp1 == "D" || NameTemp1 == "M" || NameTemp1 == "V") OPNTemp = 4;
if (NameTemp1 == "E") SNTemp = 5;
if (NameTemp1 == "N" || NameTemp1 == "W") OPNTemp = 5;
if (NameTemp1 == "F" || NameTemp1 == "X") OPNTemp = 6;
if (NameTemp1 == "O") SNTemp = 6;
if (NameTemp1 == "G" || NameTemp1 == "P" || NameTemp1 == "Y") OPNTemp = 7;
if (NameTemp1 == "H" || NameTemp1 == "Q" || NameTemp1 == "Z") OPNTemp = 8;
if (NameTemp1 == "I") SNTemp = 9;
if (NameTemp1 == "R") OPNTemp =9;
OPN += OPNTemp;
SN += SNTemp;
PODNWhole += SNTemp;
PODNWhole += OPNTemp;
i++;
}
var PODN = PODNWhole
var OPNReduceFinal = 0;
if (OPN > 9) {
var OPNLength = parseInt(OPN.toString().length);
var OPNTempString = OPN.toString();
var i = 0;
while (i < OPNLength) {
OPNReduce1 = parseInt(OPNTempString.charAt(i));
OPNReduceFinal += OPNReduce1;
i++;
}
}
var SNReduceFinal = 0;
if (SN > 9) {
var SNLength = parseInt(SN.toString().length);
var SNTempString = SN.toString();
var i = 0;
while (i < SNLength) {
SNReduce1 = parseInt(SNTempString.charAt(i));
SNReduceFinal += SNReduce1;
i++;
}
}
var PODNReduceFinal = 0;
if (PODN > 9) {
var PODNLength = parseInt(PODN.toString().length);
var PODNTempString = PODN.toString();
var i = 0;
while (i < PODNLength) {
PODNReduce1 = parseInt(PODNTempString.charAt(i));
PODNReduceFinal += PODNReduce1;
i++;
}
// var PODNReduceFinal = PODNReduce2;
// var PODN = PODNReduce2;
}
var LLNResult = "Your Life Lesson Number Is:" + LLNTemp2 + "/" + Reduction1;
if (LLNReduceFinal2 != 0) {
LLNResult = LLNResult + "/" + LLNReduceFinal2;
}
var OPNResult = "Your Outer Personality Number is:" + OPN;
if (OPNReduceFinal != 0) {
var OPNResult = OPNResult + "/" + OPNReduceFinal;
}
var SNResult = "Your Soul Number is:" + SN;
if (SNReduceFinal != 0) {
var SNResult = SNResult + "/" + SNReduceFinal;
}
var PODNResult = "Your Path of Destiny Number is:" + PODNWhole;
if (PODNReduceFinal != 0) {
var PODNResult = PODNResult + "/" + PODNReduceFinal;
}
if (LLNTemp2 != 0) {
document.getElementById("LLNResult").innerHTML = LLNResult;
}
if (PODNWhole != 0) {
document.getElementById("OPNResult").innerHTML = OPNResult;
document.getElementById("SNResult").innerHTML = SNResult;
document.getElementById("PODNResult").innerHTML = PODNResult;
}
}
</script>
</body>
</html>
So basically you enter your birthday and full name into a form. the script will then convert the name to numbers A = 1, B = 2.... and reduce both to single digits. the numbers will be added one by one. example. 13=4, 55=10, 63=9.
Here is the general code used to make reductions. Let's make PODN = 55
var PODNReduceFinal = 0;
var PODN = 55;
if (PODN > 9) {
var PODNLength = parseInt(PODN.toString().length);
var PODNTempString = PODN.toString();
var i = 0;
while (i < PODNLength) {
PODNReduce1 = parseInt(PODNTempString.charAt(i));
PODNReduceFinal += PODNReduce1;
i++;
}
}
Currently, it only loops once but I would like to have it get reduced to the lowest number possible. 1 in this case. I was thinking that if I change the if to a while it would accomplish this but it doesn't work the way I thought it would. I tried to make some changes and got stuck in a loop. So I started to troubleshoot. I added another variable to prevent the whole loop from looping infinitely.
var PODNReduceFinal = 0;
var PODN = 55;
while (PODN > 9) {
var PODNLength = parseInt(PODN.toString().length);
var PODNTempString = PODN.toString();
var i = 0;
while (i < PODNLength) {
PODNReduce1 = parseInt(PODNTempString.charAt(i));
PODNReduce2 += PODNReduce1;
i++;
}
var PODNReduceFinal = PODNReduce2;
var PODN = PODNReduce2;
}
Using this I thought when PODN would be checked by the while loop first it would run through the first steps. Get the length of the number, in this case 2. Convert it to a string so it can pull the digits one by one. Pull the digits in sequence with the length of the loop and convert them to numbers. Add them together in PODNReduce2, 55=10. Set PODNReduceFinal = 10, set PODN = 10. Then return to the first condition and check that PODN is now 10 and is greater than 9. Loop again to reduce further. Doing this until it's a single digit stored in PODNReduceFinal. But that's not what happens. When I try to display PODNReduceFinal I get NaN. Even if I revert the first "while" to "if" it still doesn't work. I'm at a loss. Please help.

Assigning static data amount in a div to be called from a function

I'm using an example based on the following example:
http://jsfiddle.net/5tt7d3e6/
In this, a function is created to turn a number into words.
The function is processed in the following HTML
<input type="text" name="number" placeholder="Number OR Amount" onkeyup="word.innerHTML=convertNumberToWords(this.value)" />
<div id="word"></div>
The above allows you to enter a number into a textbox. The function translates what you type as a number into words.
Is there an easy way to set a div which already holds the number, instead of typing it to display?'
Such as:
<div data="innerHTML=convertNumberToWords(1233213)"></div>
You can hookup an event handler for onreadystatechange and inside that you can put your logic.
Fiddle 1
document.onreadystatechange = function() {
word.innerHTML = convertNumberToWords(1233213);
};
However if you want show data based on existing value inside input, first put an id attribute for input
<input id="number" ... />
And then in JS:
document.onreadystatechange = function() {
word.innerHTML = convertNumberToWords(number.value);
};
Fiddle 2
Suggestion: use switch statment in convertNumberToWords()
switch(amount){
case 0: 'zero'; break;
default: 'Please enter number only!'; break;
}
If you want to write to the document as it is processed and not later.
<div id="word">
<script>
document.write(convertNumberToWords(12233456))
</script>
</div>
This is the recommended way though:
<div id="word"></div>
<script>
document.getElementById('word').innerHTML = convertNumberToWords(12233456);
</script>
--
<script>
function convertNumberToWords(amount) {
var words = new Array();
words[0] = '';
words[1] = 'One';
words[2] = 'Two';
words[3] = 'Three';
words[4] = 'Four';
words[5] = 'Five';
words[6] = 'Six';
words[7] = 'Seven';
words[8] = 'Eight';
words[9] = 'Nine';
words[10] = 'Ten';
words[11] = 'Eleven';
words[12] = 'Twelve';
words[13] = 'Thirteen';
words[14] = 'Fourteen';
words[15] = 'Fifteen';
words[16] = 'Sixteen';
words[17] = 'Seventeen';
words[18] = 'Eighteen';
words[19] = 'Nineteen';
words[20] = 'Twenty';
words[30] = 'Thirty';
words[40] = 'Forty';
words[50] = 'Fifty';
words[60] = 'Sixty';
words[70] = 'Seventy';
words[80] = 'Eighty';
words[90] = 'Ninety';
amount = amount.toString();
var atemp = amount.split(".");
var number = atemp[0].split(",").join("");
var n_length = number.length;
var words_string = "";
if (n_length <= 9) {
var n_array = new Array(0, 0, 0, 0, 0, 0, 0, 0, 0);
var received_n_array = new Array();
for (var i = 0; i < n_length; i++) {
received_n_array[i] = number.substr(i, 1);
}
for (var i = 9 - n_length, j = 0; i < 9; i++, j++) {
n_array[i] = received_n_array[j];
}
for (var i = 0, j = 1; i < 9; i++, j++) {
if (i == 0 || i == 2 || i == 4 || i == 7) {
if (n_array[i] == 1) {
n_array[j] = 10 + parseInt(n_array[j]);
n_array[i] = 0;
}
}
}
value = "";
for (var i = 0; i < 9; i++) {
if (i == 0 || i == 2 || i == 4 || i == 7) {
value = n_array[i] * 10;
} else {
value = n_array[i];
}
if (value != 0) {
words_string += words[value] + " ";
}
if ((i == 1 && value != 0) || (i == 0 && value != 0 && n_array[i + 1] == 0)) {
words_string += "Crores ";
}
if ((i == 3 && value != 0) || (i == 2 && value != 0 && n_array[i + 1] == 0)) {
words_string += "Lakhs ";
}
if ((i == 5 && value != 0) || (i == 4 && value != 0 && n_array[i + 1] == 0)) {
words_string += "Thousand ";
}
if (i == 6 && value != 0 && (n_array[i + 1] != 0 && n_array[i + 2] != 0)) {
words_string += "Hundred and ";
} else if (i == 6 && value != 0) {
words_string += "Hundred ";
}
}
words_string = words_string.split(" ").join(" ");
}
return words_string;
}
</script>
<div id="word">
<script>
document.write(convertNumberToWords(12233456))
</script>
</div>
Fiddle Link
change the value of textbox and press click button it will return into word
<input id="check"type="text" name="number" placeholder="Number OR Amount" />
<div id="word"></div>
<input type="button" id="button" value="click">
js code
$("#button").click(function()
{
var number = $('#check').val();
$("#word").html(toWords(number));
});
var th = ['','thousand','million', 'billion','trillion'];
var dg = ['zero','one','two','three','four', 'five','six','seven','eight','nine']; var tn = ['ten','eleven','twelve','thirteen', 'fourteen','fifteen','sixteen', 'seventeen','eighteen','nineteen']; var tw = ['twenty','thirty','forty','fifty', 'sixty','seventy','eighty','ninety']; function toWords(s){s = s.toString(); s = s.replace(/[\, ]/g,''); if (s != parseFloat(s)) return 'not a number'; var x = s.indexOf('.'); if (x == -1) x = s.length; if (x > 15) return 'too big'; var n = s.split(''); var str = ''; var sk = 0; for (var i=0; i < x; i++) {if ((x-i)%3==2) {if (n[i] == '1') {str += tn[Number(n[i+1])] + ' '; i++; sk=1;} else if (n[i]!=0) {str += tw[n[i]-2] + ' ';sk=1;}} else if (n[i]!=0) {str += dg[n[i]] +' '; if ((x-i)%3==0) str += 'hundred ';sk=1;} if ((x-i)%3==1) {if (sk) str += th[(x-i-1)/3] + ' ';sk=0;}} if (x != s.length) {var y = s.length; str += 'point '; for (var i=x+1; i<y; i++) str += dg[n[i]] +' ';} return str.replace(/\s+/g,' ');}

Birthdate Validation in JavaScript

I'm trying to validate a Birthday date but I can only validate if all filled in.
If I just choose date, there is no alert ("day must be chosen / month must be chosen").
I can't validate a date...
How to run this validation?
function isbday(day,month,year) {
var mth = month;
var dy = day;
var yr = year;
if((mth < 1) || (mth > 12));
else if((dy < 1) || (dy > 31));
else if(((mth == 4) || (mth == 6) || (mth == 9) || (mth == 11)) && (dy > 30));
else if((mth == 2) && (((yr % 400) == 0) || ((yr % 4) == 0)) && ((yr % 100) != 0) && (day > 29));
else if((mth == 2) && ((yr % 100) == 0) && (dy > 29));
else if((mth == 2) && (dy > 28)) valid = false;
return false;
alert("Birthdate must be filled");
}
function validate(){
var day = document.getElementsByName("xday")[0].value;
var month = document.getElementsByName("xmonth")[0].value;
var year = document.getElementsByName("xyear")[0].value;
if(day,month,year == null || day,month,year == ""){
alert("Birthdate must be filled");
}else if(birthdate.match(isbday(birthdate))){
alert("Birthdate must be filled");
}else
{
alert("Birthdate success");
}
}
<tr>
<td >Birthdate </td>
<td><select name="xday">
<option value="">Date</option>
<script>
var myDate = new Date();
var year = myDate.getFullYear();
for(var i = 1; i < 32; i++){
document.write('<option value="'+i+'">'+i+'</option>');
}
</script>
</select>
<select name="xmonth">
<option value="">Month</option>
<script>
var myDate = new Date();
var year = myDate.getFullYear();
for(var i = 1; i < 13; i++){
document.write('<option value="'+i+'">'+i+'</option>');
}
</script>
</select>
<select name="xyear">
<option value="">Year</option>
<script>
var myDate = new Date();
var year = myDate.getFullYear();
for(var i = 1950; i < year; i++){
document.write('<option value="'+i+'">'+i+'</option>');
}
</script>
</select>
</td>
</tr>
<tr>
<td>
<input type="button" name="btnRegis" onClick="validate()" onsub value="Register"/>
</td>
</tr>
I think the best way is to change the day select according to the month that was selected but if you still want to do it the same way:
Change a little bit your valid function
Each if statement return false if not valid
function isVaild(day, month, year) {
var mth = month;
var dy = day;
var yr = year;
//Checks
if ((mth < 1) || (mth > 12)) return false;
else if ((dy < 1) || (dy > 31)) return false;
else if (((mth == 4) || (mth == 6) || (mth == 9) || (mth == 11)) && (dy > 30)) return false;
else if ((mth == 2) && (((yr % 400) == 0) || ((yr % 4) == 0)) && ((yr % 100) != 0) && (day > 29)) return false;
else if ((mth == 2) && ((yr % 100) == 0) && (dy > 29)) return false;
else if ((mth == 2) && (dy > 28)) return false;
//Pass all checks
return true;
}
function validate() {
var day = document.getElementsByName("xday")[0].value;
var month = document.getElementsByName("xmonth")[0].value;
var year = document.getElementsByName("xyear")[0].value;
//if one is empty
if (day, month, year === null || day, month, year === "") {
alert("Birthdate must be filled\nDay, Month, Year is empty");
}
//if not a vaild date
else if (!isVaild(day, month, year)) {
alert("Birthdate not vaild");
}
//All good :)
else {
alert("Birthdate success");
}
}
Working example here

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

Categories

Resources