JavaScript Math to PHP Page ID - javascript

I'm trying to create a form that takes a birthdate, adds up all the digits, then uses the result to query the database and display the results. The sum has to be a number between 1 an 22 in order for it to choose from the database.
I have the form button to trigger the function getBirthCard, but on click it simply spits the value of the form inputs into the URL.
Can anyone give me an idea of what's not coded properly in order for this to work? Please and thank you!
<script language="JavaScript" type="text/javascript">
function getBirthCard() {
var month = lpn.month.value;
var day = lpn.day.value;
var Byear = lpn.year.value;
var century = Byear.substring (0,2);
var year = Byear - century*100;
sum = parseInt(day) + parseInt(month) + parseInt(century) + parseInt(year);
reduce();
results(sum);
}
function reduce(){
var first; // first one or two digits
var last; // last digit
var sumStr = "" + sum;
// while number is bigger than 22
while (sum > 22) {
// if it is a three digit number
if (sum > 99) {
first= sumStr.substring(0,2);
last= sumStr.substring(2);
sum = parseInt(first) + parseInt(last);
sumStr = "" + sum;
// if it is a two digit number
} else {
first= sumStr.substring(0,1);
last= sumStr.substring(1);
sum = parseInt(first) + parseInt(last);
sumStr = "" + sum;
}
} // end while
} // end reduce
}
function results()
{
window.location.assign("http://arcanabazaar.com/results.php?id=' + sum")
}
</script>
Here's the form that I'm using:
<form class="form-inline" action="" name="lpn" method="GET">
<input type="text" id="month" name="month" placeholder="08">
<input type="text" id="day" name="day" placeholder="20">
<input type="text" id="year" name="year" placeholder="1987">
<br><br>
<button type="submit" onclick="getBirthCard()" class="btn btn-large">What's My Card?</button>
</form>

I'm guessing you're choosing a card from the major arcana based on the birthday digits. If you don't care too much about how this is calculated, here's a quick way to do it using modular arithmetic:
function getBirthCard() {
var month = document.getElementById("month").value;
var day = document.getElementById("day").value;
var year = document.getElementById("year").value;
var sum = parseInt(month) + parseInt(day) + parseInt(year);
var card = sum % 22 + 1; // this is always from 1 to 22
window.location.assign('http://arcanabazaar.com/results.php?id=' + card);
return false;
}
The button to call this must be coded as:
<button type="submit" onclick="return getBirthCard();" class="btn btn-large">What's My Card?</button>
The OnClick event must return false, so that it doesn't continue to actually submit the form. That's why it was sending the month, day, year values directly previously.
This will give different results than your code was intending, but perhaps this will suffice.
(EDIT: Replaced lpn.month.value by document.getElementById("month").value etc.)
(EDIT2: Return false to onclick caller.)
EDIT3: Here's code to repeatedly add the digits together until they are less than or equal to 22:
function getBirthCard() {
var month = document.getElementById("month").value;
var day = document.getElementById("day").value;
var year = document.getElementById("year").value;
var card = getCardFromDate( month, day, year );
window.location.assign('http://arcanabazaar.com/results.php?id=' + card);
return false;
}
function getCardFromDate( month, day, year )
{
var sum = parseInt('' + month + day + year);
while( 22 < sum )
{
var digits = (''+sum).split('');
sum = 0;
for( var i=0 ; i<digits.length ; ++i ) sum += parseInt(digits[i]);
}
return sum;
}

Related

How to retain leading zeroes when converting String to Number in javascript

How can I convert a string to number without loosing the trailing zeroes
var string1 = '02';
Number(string1); // == 2 - Default output
Number(string1); // == 02 - My requirement
The reason why I want this is: I am passing a date as value to the date HTML element. And the format is yyyy-MM-dd, month and date format is two digits and if I convert the date (string in my case) to number the leading zeroes are being removed.
You can't. A Number is a Number, period. You can make a helper object to have a number and a number leftpad method at your disposal. Something like:
document.querySelector("button").addEventListener("click", setDateValueExample);
var num = XNumber(3);
var result = {
el: document.querySelector("#result"),
log(str) {
this.el.textContent += str + '\n';
}
}
// XNumber usage example
result.log('XNumber(54).lpad(1000000): ' + XNumber(54).lpad(1000000));
// Datefield value from date field formatting example
var d = new Date(document.querySelector("#somedate").value);
result.log('Date formatted: ' +
[XNumber(d.getMonth()+1).lpad(),
XNumber(d.getDate()).lpad(),
d.getFullYear()].join('-'));
// Set date field value from string example
function setDateValueExample() {
document.querySelector("#somedate").value =
document.querySelector("button").getAttribute("data-dateString")
.split("/")
.reverse()
.map(function (v) {
return XNumber(v).lpad()
})
.join('-');
}
// The actual Number helper
function XNumber(num) {
return {
num: +num,
lpad (base) {
base = base || 10;
var len = (String(base).length - String(this.num).length)+1;
return len > 0 ? new Array(len).join('0')+this.num : this.num;
}
};
}
<input type="date" id="somedate" value="2017-02-01"/> a date
<button data-dateString="2/3/2017">Set value from string "2/3/2017"</button>
<pre id="result"></pre>
As commented, you can use ("00" + num).slice(-2).
You can try something like this:
function getParsedValue(date) {
var d = date;
if (typeof d === "string") {
d = new Date(date);
}
return [d.getFullYear(), getDoubleDigitString(d.getMonth() + 1), getDoubleDigitString(d.getDate())].join("-")
}
function getDoubleDigitString(num) {
return ("00" + num).slice(-2);
}
var date = new Date();
document.getElementById('txtDate1').value = getParsedValue(date)
document.getElementById('txtDate2').value = getParsedValue("1999/1/2")
<input type="date" id="txtDate1" />
<input type="date" id="txtDate2" />

Average of input prompt numbers

I am having an issue with getting the average of the numbers that are inputted through a prompt window. I need to display the numbers like i have so far, but I can't seem to get them to add together to get the average.
here is my code so far.
<html>
<body>
<script type="text/javascript">
function show_prompt() {
i = 0;
do {
var number = prompt("Please Enter a Number");
var number = parseInt(number);
i++;
document.write("Number: " + number);
document.write("<br>");
}
while (i < 5);
}
show_prompt();
var avrg = number + number + number + number + number
document.write('Average of scores : ' + avrg);
</script>
</body>
</html>
You have to move calculation inside function. Also you can do it simplier:
function show_prompt() {
var i = 0;
var sum = 0;//declare a variable to keep the sum of numbers
do {
var number = prompt("Please Enter a Number");
sum += parseInt(number); //sum the numbers here
i++;
document.write("Number: " + number);
document.write("<br>");
}
while (i < 5);
document.write('Average of scores : ' + sum / i);//use the sum of the numbers divide by the the numbers the user enters
}
show_prompt();
Tried to comment your old code with the mistakes:
function show_prompt() {
i = 0;
do {
//there is no need to declare number twice
//also you don't sum somewhere the numbers you get from the user
var number = prompt("Please Enter a Number");
var number = parseInt(number);
i++;
document.write("Number: " + number);
document.write("<br>");
}
while (i < 5);
}
show_prompt();
//number is out of scope of function show_prompt so is undefined
var avrg = number + number + number + number + number
//to get an avg you have to divide the sum by the number
document.write('Average of scores : ' + avrg);
Notice your var number is scoped within show_prompt(), it is not visible outside of it.
You need to have your show_prompt function not loop, and return the number, and have another function that calls show_prompt multiple times, takes the returns and calculate the average.. Also, your code is just calculating the sum, not the average
I'm not going to show you the exact code, but here's the idea
calc_average:
var sum=0;
loop 5 times:
sum = sum + show_prompt();
average = sum/5;
show_prompt:
var number = prompt('blah blah');
return number

JQuery setting a number format

I'm using JQuery and I'm having a problem trying to sort out how to increase a number.
The record number is something like 1364-14-1234.
The number format works like this:
1364 - Member number
14 - Year in 2 digit format
1234 - in the number which needs to be increased.
The problem is how do I add a leading zero to the number to keep a 4 digit number if the number is 0123.
<div id="member_id">1364-14-0001</div>
var data = $('#member_id').text();
var arr = data.split('-');
var num = arr[2];
num++;
$("#member_id").html(arr[0] + " - " + arr[1] + " - " + num);
My JSfiddle
Something like this maybe
function pad(numb, len) {
while (numb.toString().length < len) numb = '0' + numb;
return numb;
}
$('#member_id').text(function(_, txt) {
var arr = txt.split('-'),
len = arr[2].length;
arr[2] = pad(+(arr[2]) + 1, len);
return arr.join('-')
});
FIDDLE

Counter is not updated and it's value is replaced by the current value

I'm using 4 drop-down lists in an html form. The 2 drop downs, represent the starting and ending month of an activity and the other 2 represent the starting and the ending year of an activity. I'm allowing the user to enter a 3 year history and after completion, I prompt the user to go to the next section. To calculate the 3 year history, I take the difference between the start and ending month and I enter it each time in a counter (note that I am working with numbers and not with the Date object). The values are passed into my arrays, but the counter is not updated. It is just replaced by the new value in the array. Can anyone tell me where is the problem? Here is my code:
var arrMonthStarted = []; //It stores the month that activity started
var arrMonthEnded = []; //It stores the month that activity ended
var arrYearStarted = []; //It stores the year that activity started
var arrYearEnded = []; //It stores the year that activity ended
function validatedropdowns1(){
var monthStarted = document.getElementById('idMonthStarted').value;
var yearStarted = document.getElementById('idYearStarted').value;
var monthEnded = document.getElementById('idMonthEnded').value;
var yearEnded = document.getElementById('idYearEnded').value;
arrMonthStarted.push(monthStarted);
arrMonthEnded.push(monthEnded);
arrYearStarted.push(yearStarted);
arrYearEnded.push(yearEnded);
//Calculating the 3-year history
var count = 0;
if(yearStarted == yearEnded){
if(monthEnded < monthStarted){
var temp = monthEnded;
monthEnded = monthStarted;
monthStarted = temp;
}
var diffmonths = monthEnded - monthStarted;
count = count + diffmonths;
}
//Take the difference between the years.
var subYears = yearEnded - yearStarted;
//If 1, just take the difference on the first 2 lines of the calendar
if(subYears == 1){
var subLine1 = 12 - monthStarted;
var subLine2 = 12 - monthEnded;
var finalLine2 = 12 - subLine2;
var takeresult = subLine1 + finalLine2;
count = count + takeresult;
}
//Follow case 1, but also add 12 months
if(subYears == 2){
var subLine3 = 12 - monthStarted;
var subLine4 = 12 - monthEnded;
var finalLine3 = 12 - subLine4;
var takeresult11 = subLine3 + finalLine4;
var takeresult1 = 12 + takeresult11;
count = count + takeresult1l;
}
//add another 12 months (24 now) on step 1.
if(subYears == 3){
var subLine5 = 12 - monthStarted;
var subLine6 = 12 - monthEnded;
var finalLine5 = 12 - subLine6;
var takeresult22 = subLine5 + finalLine6;
var takeresult2 = 24 + takeresult22;
count = count + takeresult2;
}
var arrCount = []; // array to hold the count var
arrCount.push(count); // push count into arrCount
//print total months
for(var m = 0; m < arrCount.length; m++){
alert("The array now has" + "" + "" + count + "" + "months");
}
if(arrCount == 36){
alert("You have successfuly finished this section. Please go to the next section. Thank you.")
document.getElementById('btnAdd').disable = true;
}
if(arrMonthEnded[arrMonthEnded.length - 1] - arrMonthStarted[arrMonthSarted.length] > 1){
alert("There should not be a gap of more than a month in your 3 year activity. Fill in all the months and select from the list what you were doing each month. Thank you.")
}
}
Also, I was trying to test the gap between the end date and the next start date. For example if I enter 12 2011 as an end date and 03 2012 as the next start date, I would like to see if there is a gap of more than one month. I tried the code below, but it didn't work
if(arrMonthEnded[arrMonthEnded.length - 1] - arrMonthStarted[arrMonthSarted.length] > 1){
alert("There should not be a gap of more than a month in your 3 year activity. Fill in all the months and select from the list what you were doing each month. Thank you.")
}
Thank you in advance (KSFIDDLE http://jsfiddle.net/k4dNb/)
This loop is pointless, as the array will only ever have one item:
for(var m = 0; m < arrCount.length; m++){
Here you are comparing an array to a number, and eventhough that actually works because both will be converted to strings, and the string value of [36] is "36" which is the same as the string value of 36 which is "36", it's done in a confusing way:
if(arrCount == 36){
Typo, you wrote arrMonthSarted instead of arrMonthStarted:
if(arrMonthEnded[arrMonthEnded.length - 1] - arrMonthStarted[arrMonthSarted.length] > 1){
Also, arrMonthStarted[arrMonthStarted.length] will always return undefined, as you are trying to access an item beyond the last item of the array.

South African ID Number Validate and Get Age and Gender

I've researched this but none of the code I use seems to work. South African ID numbers contain date of birth and gender. All I want is it to pull in that information and verify it when their ID number is entered into an input field, preferably in jQuery or javascript
Any help is appreciated,
Dawid
You could use Koenyn's regex validation, not so sure how a single-digit number (0-9?) from the input represents the gender but basing on this tool you provided and David Russell's Using Javascript to validate South African ID Numbers, here's an untested attempt:
UPDATE 1:
After following this thread, What is a South African ID number made up of?, I updated my implementation to include the gender and citizenship tests.
UPDATE 2:
Forgot to wrap the month number increment id_month + 1 within the date string fullDate, updating solution with Dawid's fix.
HTML Markup:
<div id="error"></div>
<form id="idCheck">
<p>Enter the ID Number: <input id="idnumber" /> </p>
<p> <input type="submit" value="Check" /> </p>
</form>
<div id="result"> </div>
Javascript:
function Validate() {
// first clear any left over error messages
$('#error p').remove();
// store the error div, to save typing
var error = $('#error');
var idNumber = $('#idnumber').val();
// assume everything is correct and if it later turns out not to be, just set this to false
var correct = true;
//Ref: http://www.sadev.co.za/content/what-south-african-id-number-made
// SA ID Number have to be 13 digits, so check the length
if (idNumber.length != 13 || !isNumber(idNumber)) {
error.append('<p>ID number does not appear to be authentic - input not a valid number</p>');
correct = false;
}
// get first 6 digits as a valid date
var tempDate = new Date(idNumber.substring(0, 2), idNumber.substring(2, 4) - 1, idNumber.substring(4, 6));
var id_date = tempDate.getDate();
var id_month = tempDate.getMonth();
var id_year = tempDate.getFullYear();
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)))) {
error.append('<p>ID number does not appear to be authentic - date part not valid</p>');
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) {
error.append('<p>ID number does not appear to be authentic - check digit is not valid</p>');
correct = false;
};
// if no error found, hide the error message
if (correct) {
error.css('display', 'none');
// clear the result div
$('#result').empty();
// and put together a result message
$('#result').append('<p>South African ID Number: ' + idNumber + '</p><p>Birth Date: ' + fullDate + '</p><p>Gender: ' + gender + '</p><p>SA Citizen: ' + citzenship + '</p>');
}
// otherwise, show the error
else {
error.css('display', 'block');
}
return false;
}
function isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
$('#idCheck').submit(Validate);
DEMO: http://jsfiddle.net/chridam/VSKNx/
this is the validation regex we us at our company:
string IdExpression = #"(?<Year>[0-9][0-9])(?<Month>([0][1-9])|([1][0-2]))(?<Day>([0-2][0-9])|([3][0-1]))(?<Gender>[0-9])(?<Series>[0-9]{3})(?<Citizenship>[0-9])(?<Uniform>[0-9])(?<Control>[0-9])";
as far as using regex, it's really simple
http://www.w3schools.com/jsref/jsref_obj_regexp.asp
There is a jQuery plugin that you can use. Check it out at http://www.verifyid.co.za/jqueryid
So there is an issue where if the ID number starts with 0 it gives the year of birth 1901 instead of 2001. #louwki mentioned it in his comment
I'm using your code but running into an issues when adding a id number
010101.... it gives the year of birth 1901 instead of 2001 any work around for this?
I have a work around assuming that there is no one older than a 100 years still alive who wants to get their date
// get first 6 digits as a valid date
var tempDate = new Date(idNumber.substring(0, 2), idNumber.substring(2, 4) - 1, idNumber.substring(4, 6));
var id_date = tempDate.getDate();
var id_month = tempDate.getMonth();
var id_year = tempDate.getFullYear();
// Add a 100 years to the current year if older than 100 years
if(id_year < (new Date()).getFullYear() - 100){
id_year+= 100
}
var fullDate = id_date + "-" + id_month + 1 + "-" + id_year;
DEMO: http://jsfiddle.net/dupies/5fwxvu6d/3/

Categories