Javascript College CA Bug - javascript

I have an error in my code.
The objective is that if the user buys enough jersey's that is over €250 I have to discount everything that comes next after it at 15%.
The first part of my code works (If cost <= 250) the anything above gives me a (NaN).
My code is as follows:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>
Q1 - Jerseys
</title>
<style type="text/css">
</style>
<script>
"use strict";
function processOrder()
{
//Calculations for Order
var type = document.getElementById("getType").value;
var number = parseInt(document.getElementById("getNumber").value);
var cost;
var PER_FIVE = parseFloat(0.15);
var overPrice = cost - 250;
//Logo Variables
var logo = document.getElementById("getLogo").value || "N";
var logoCost = 1.50;
//Empty Variables for Returned Values
var outputText;
//Polo Shirt Case
if (type === "Polo" && logo === "Y")
{
cost = (number * (22.50 + logoCost));
} else if (type === "Polo" && logo === "N") {
cost = parseFloat(number * 22.50);
}//End Polo
//Short Sleeve Case
if (type === "Short" && logo === "Y") {
cost = (number * (22.50 + logoCost));
} else if (type === "Short" && logo === "N") {
cost = number * 25.50;
}//End Short
//Long Sleeve Case
if (type === "Long" && logo === "Y") {
cost = (number * (22.50 + logoCost));
} else if (type === "Long" && logo === "N") {
cost = number * 28.50;
}//End Long
//Output To "results" Text Area
if (cost <= 250) {
outputText = "The cost of your jerseys is €" + cost;
document.getElementById("results").value = outputText;
} else if (cost > 250) {
outputText = "The cost of your jerseys is €" + (250 + (overPrice - (overPrice * PER_FIVE)));
document.getElementById("results").value = outputText;
}//End If
}//End Function
</script>
</head>
<body>
Please Enter details of your jersey order:
<br> <br>
Type of jersey (Polo, Short,Long):
<input id="getType" />
<br> <br>
Number of Jerseys:
<input id="getNumber" />
<br> <br>
Add A Logo:
<input id="getLogo" maxlength="1"/> Type: "Y" or "N".
<br> <br>
<button onclick="processOrder()" >Click to see results below</button>
<br> <br>
Results:
<br>
<textarea id="results" rows="4" cols="50" readonly >
</textarea>
</body>
</html>

You're assigning overPrice before cost has been determined:
var overPrice = cost - 250;
At this point cost is undefined, and undefined - 250 is what's giving you NaN.
Variables aren't dynamic in this way - updating cost won't automatically update overPrice - you need to set it once you know the value of cost. Within your else if block would be appropriate since it is not needed elsewhere:
//Output To "results" Text Area
if (cost <= 250) {
outputText = "The cost of your jerseys is €" + cost;
document.getElementById("results").value = outputText;
} else if (cost > 250) {
var overPrice = cost - 250;
outputText = "The cost of your jerseys is €" + (250 + (overPrice - (overPrice * PER_FIVE)));
document.getElementById("results").value = outputText;
}//End If
On a separate note, you're using parseInt without specifying the radix parameter. It's recommended to always specify it to avoid potential issues:
var number = parseInt(document.getElementById("getNumber").value, 10);

Related

What is missing from my discount code to make this work? Am I missing a variable?

I thought I had everything correct and I still can't seem to figure out why the function isn't working out the way it is supposed to. I have this issue where the code is having a reference error but I'm not sure how to define the function. I also put it through the W3 validator but that's not telling me anything.
<!DOCTYPE HTML>
<html lang="en-us">
<head>
<meta charset="utf-8">
<title>discount amount</title>
</head>
<body>
<script>
/* Input: purchase amount
* Processing: determine through if statements if they get a discount
* Output: final price after tax
*/
// Computes and returns a discounted purchase amount.
function getDiscountedAmount(purchase) {
var purchase =
parseInt(document.getElementById('purchase').value);
var dayOfWeek = new Date().getDay();
var output = document.querySelector("#output");
let rate;
if (purchase < 50) {
rate = 0.06;
} else if (purchase < 100 && [2, 3].includes(dayOfWeek)) {
rate = 0.06;
} else if (purchase < 500 && [2, 3].includes(dayOfWeek)) {
rate = 0.06;
}
let discount = purchase * rate;
return purchase - discount;
output.innerHTML = "$" + String(getDiscountedAmount(200));
}
</script>
Please enter your final price: <input type="text" id="purchase" size="5">
<br>
<button type="button" onclick="getDiscountedAmount(purchase)">discount?
</button>
<div id="output"></div>
</body>
</html>
The first line of your function already is wrong, you're trying to get a float number from nothing and you're overriding your input parameter to the function
var purchase = parseFloat();
Try:
purchase = parseFloat(purchase);
so that it uses your input parameter.
Also I'm not too sure about your date comparison dayOfWeek == (2, 3), I don't know if that works, I've never seen that before, I personally use [2, 3].includes(dayOfWeek)
And lastly your function returns a value but then you don't see that value anywhere, try using
console.log(getDiscountedAmount(200)) or whatever your price is
In terms of your input and output you want to use DOM manipulation to get the input and show the output.
If you want to see the value in your "output" then
var output = document.querySelector("#output");
output.innerHTML = "$" + String(getDiscountedAmount(200));
Would be a simple DOM mechanism, but it's not the cleanest
One more tip is to put your script tags lastly in the body, because you want all your HTML elements "defined" first before you try to access them
Altogether a cleaner version of your code:
<!DOCTYPE HTML>
<html lang="en-us">
<head>
<meta charset="utf-8">
<title>discount amount</title>
</head>
<body>
Please enter your final price: <input type="text" id="myInput" size="5" /><br />
<button type="button" id="myButton">discount?</button>
<div id="myOutput"></div>
<script>
var myInput = document.querySelector("#myInput");
var myOutput = document.querySelector("#myOutput");
var myButton = document.querySelector("#myButton");
myButton.onclick = function() {
// Computes and returns a discounted purchase amount.
var purchase = parseFloat(myInput.value);
var dayOfWeek = new Date().getDay();
var rate;
if (purchase < 50) {
rate = 0.06;
} else if (purchase < 100 && [2, 3].includes(dayOfWeek)) {
rate = 0.06;
} else if (purchase < 1000) {
rate = 0.025;
} else {
rate = 0.03;
}
let discount = purchase * rate;
var finalPrice = purchase - discount;
output.innerHTML = "$" + String(finalPrice);
};
</script>
</body>
</html>
I changed around some ID's and moved the onclick into your JavaScript for cleaner code overall, as we like to separate the HTML from the JS
When you load your script you get an Uncaught SyntaxError because you closed your function with two }. To fix this just delete line 31.
In your first line of the function you are using parseFloat(); wrong:
var purchase = parseFloat();
Do:
var purchase = parseFloat(purchase);
Than you need to get your input number.
getDiscountedAmount(purchase) in the onclick event doesn't work.
You can use this:
var purchase = document.getElementById("purchase").value; // get value from text field
purchase = parseFloat(purchase); // convert to float
In the end you have to do this to show the number in you output div:
let output = purchase - discount;
document.getElementById("output").innerText = output; // set discont into your output div
return output;
Here is your code and how i fixed it:
<!DOCTYPE HTML>
<html lang="en-us">
<head>
<meta charset="utf-8">
<title>discount amount</title>
<script>
/* Input: purchase amount
* Processing: determine through if statements if they get a discount
* Output: final price after tax
*/
// Computes and returns a discounted purchase amount.
function getDiscountedAmount(purchase) {
var purchase = document.getElementById("purchase").value; // get value from text field
purchase = parseFloat(purchase); // convert to float
var dayOfWeek = new Date().getDay();
var rate;
if (purchase < 50) {
rate = 0.06;
}
else if (purchase < 100 && dayOfWeek ==(2,3)) {
rate = 0.06;
}
else if (purchase < 1000) {
rate = 0.025;
}
else {
rate = 0.03;
}
let discount = purchase * rate;
let output = purchase - discount;
document.getElementById("output").innerText = output; // set discont into your output div
return output;
}
</script>
</head>
<body>
Please enter your final price: <input type="text" id="purchase" size="5"><be>
<button type="button" onclick="getDiscountedAmount()">discount?</button>
<div id="output"></div>
</body>
</html>
I didn't change your return statement and dayOfWeek because i don't know how you exactly want to use it.
Here is what you are looking for:
body{margin:0;padding:0;font-family:arial;background:rgb(30,30,30);height:100vh;width:100%}.wrapper{background:lightgrey;background:linear-gradient(318deg,rgba(217,123,123,1) 0%,rgba(135,249,255,1) 100%);width:80%;height:126px;position:relative;top:calc(50vh - 63px);left:10%;padding:3px;border-radius:12px}.content{background:rgb(80,80,80);background:rgba(0,0,0,.5);border-radius:10px;width:calc(100% - 24px);padding:12px}label{font-weight:700;color:#fff}input{width:calc(100% - 16px);margin-top:4px;padding:6px;border:2px solid #fff;border:2px solid rgba(0,0,0,.3);color:#fff;background:#fff;background:rgba(0,0,0,.5);border-radius:6px;font-size:14pt}::placeholder{color:#fff;color:rgba(255,255,255,.8)}input:focus{outline:none;border:2px solid #fff;border:3px solid rgba(0,0,0,.6);padding:5px}.output-container{display:inline-block;float:right;width:180px;padding:8px;color:#fff;background:#fff;background:rgba(0,0,0,.5);font-size:12pt;margin-top:4px;border-radius:6px;font-size:14pt}button{margin-top:4px;width:150px;border:0;border-radius:6px;padding:8px;background:gray;background:rgba(0,0,0,.6);color:#fff;font-weight:700;font-size:14pt;transition:0.25s ease}button:focus{outline:none;}button:hover{cursor:pointer;background:gray;background:rgba(0,0,0,.8)}#media only screen and (max-width:400px){.wrapper{width:calc(100% - 6px);height:auto;top:0;left:0;border-radius:0}.output-container,button{width:calc(50% - 12px)}}
<!DOCTYPE HTML>
<html lang="en-us">
<head>
<meta charset="utf-8">
<title>discount amount</title>
</head>
<body>
<div class='wrapper'>
<div class='content'>
<label>Please enter your final price:</label><input type="text" autocomplete="off" placeholder='Enter price...' id="purchase" size="5">
<button type="button" onclick="getDiscountedAmount()">See discount</button>
<div class='output-container'>Total: <span id='output'>--</span></div>
</div>
</div>
<script>
//Get the output element
outputEl = document.getElementById("output");
function getDiscountedAmount() {
//Gets the value of your input
var purchase = parseFloat((document.getElementById('purchase').value).replace(/[^\d]/g,""));
var dayOfWeek = new Date().getDay();
var rate;
if (purchase < 50) {
rate = 0.06;
} else if (purchase < 100 && [2, 3].includes(dayOfWeek)) {
rate = 0.06;
} else if (purchase < 500 && [2, 3].includes(dayOfWeek)) {
rate = 0.06;
}
else {
rate = 0.03;
}
let discount = purchase * rate;
let output = purchase - discount;
//Checks if output is a number.
if(isNaN(output)){
output = 'Not a number!';
} else{
output = '$' + output;
}
//Puts the output inside of your "output" <div>
outputEl.textContent = output;
}
</script>
</body>
</html>

Input not being read by code in JavaScript

I'm having trouble with my JS form. So I'm creating a change calculator which takes in two input values - the price and cash. When I explicity put in the actual values inside JS code (like the ones I commented out after confirmValues()), it works just fine. But when I put it in the actual input box, it doesn't give work anymore. Is there something weird with my HTML or JS? Thanks!
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=">
<title> Change calculator</title>
</head>
<body>
<form>
How much does the item cost? <input type="number" id="price" name ="price"/>
<br/> <br/>
How much cash do you have? <input type="number" id="cash" name="cash"/><br/> <br/>
<input type="button" value="Enter" onclick="confirmItems();"/>
</form>
<p id="confirmation"></p>
<p id ="change"></p>
</body>
var itemCost = document.getElementById("price");
var cash = document.getElementById("cash");
var confirmation = document.getElementById("confirmation");
function confirmItems() {
confirmation.innerHTML = "Your total purchase costs $" + itemCost.value + " and you have $" + cash.value + " to pay for it.";
createConfirmationBtn();
}
function createConfirmationBtn() {
let confirmationBtn = document.createElement("BUTTON");
const confirmationBtnText = document.createTextNode("Confirm");
confirmationBtn.appendChild(confirmationBtnText);
confirmation.appendChild(confirmationBtn);
confirmationBtn.onclick = function() {
confirmValues();
}
}
let changeEl = document.getElementById("change");
function confirmValues() {
if (parseFloat(cash.value) < parseFloat(itemCost.value)) {
changeEl.innerHTML = "Not enough cash";
} else if (parseFloat(cash.value) == parseFloat(itemCost.value)) {
changeEl.innerHTML = "Your change is $0.";
} else {
calculateChange();
}
}
// cash.value = 500;
// itemCost.value = 33.44;
let remainder = parseFloat(cash.value) - parseFloat(itemCost.value);
let finalOutput = new Array();
function calculateChange() {
while (remainder > 0) {
if (remainder >= 100) {
findChange(100.00);
} else if (remainder >= 50.00) {
findChange(50.00);
} else if (remainder >= 20.00) {
findChange(20.00);
} else if (remainder >= 10.00) {
findChange(10.00);
} else if(remainder >= 5.00) {
findChange(5.00);
} else if (remainder >= 1.00) {
findChange(1.00);
} else if (remainder >= 0.25) {
findChange(0.25);
} else if (remainder >= 0.10) {
findChange(0.10);
} else if (remainder >= 0.05) {
findChange(0.05);
} else {
findChange(0.01);
}
}
changeEl.innerHTML = finalOutput;
}
function findChange(value) {
//Step 1. Get number of dollar for each type of dollar
let dValue = parseInt(remainder / value);
// Step 2. Storing numDValue in an array
finalOutput.push("[$" + value + " x" + dValue+"]");
remainder = parseFloat(remainder - (value * dValue));
remainder = parseFloat(remainder.toFixed(2));
}
You need to have the vars inside the functions that need them or they will not pick up what the user enters
You can show and hide the confirm button
DRY, Don't Repeat Yourself
function confirmValues() {
let itemCost = document.getElementById("price").value;
let cash = document.getElementById("cash").value;
const confirmation = document.getElementById("confirmation");
const changeEl = document.getElementById("change");
const confirm = document.getElementById("confirm");
cash = isNaN(cash) || cash === "" ? 0 : +cash; // test valid input
itemCost = isNaN(itemCost) || itemCost === "" ? 0 : +itemCost;
if (cash < itemCost) {
changeEl.innerHTML = "Not enough cash";
} else {
confirmation.innerHTML = "Your total purchase costs $" + itemCost.toFixed(2) + " and you have $" + cash.toFixed(2) + " to pay for it.";
changeEl.innerHTML = "Your change is $" + (cash - itemCost).toFixed(2);
confirm.classList.remove("hide");
}
}
.hide {
display: none;
}
<title> Change calculator</title>
<form>
How much does the item cost? <input type="number" id="price" name="price" />
<br/> <br/> How much cash do you have? <input type="number" id="cash" name="cash" /><br/> <br/>
<input type="button" value="Enter" onclick="confirmValues();" />
<input type="button" id="confirm" class="hide" value="Confirm" onclick="alert('Confirmed!')" />
</form>
<p id="confirmation"></p>
<p id="change"></p>

Trying to reset my variables to their starting value javascript

This is actually my first beginner project. I wrote the whole code myself. It's about buying phones through 3 different methods. You can tell the program to automatically buy all phones and phone masks for all money you got, to manually buy one by one or to enter a number of phones and masks you wanna buy. Together with all that I set a number of phones and masks available at the stop together with user's bank balance.
The problem's coming from eraseData function. It simply doesn't work. Actually, the first part of it works but the second where I'm trying to reset my variables to their original value isn't working.
I have problems with using this editor to put in my code so I will use Pastebin.
const PHONE_PRICE = 150.00;
const MASK_PRICE = 50;
var bankBalance = 1983;
var aPhones = 11;
var aMasks = 11;
var boughtPhones = 0;
var boughtMasks = 0;
function eraseData(){
var bankBalance = 1800;
var aPhones = 11;
var aMasks = 11;
var boughtPhones = 0;
var boughtMasks = 0;
var check = false;
var quantity = 0;
document.getElementById("money").innerHTML = "Money left: $" + bankBalance;
document.getElementById("phones").innerHTML = "Amount of phones: " + boughtPhones;
document.getElementById("masks").innerHTML = "Amount of phone masks: " + boughtMasks;
}
function updateData(){
document.getElementById("money").innerHTML = "Money left: $" + bankBalance;
document.getElementById("phones").innerHTML = "Amount of phones: " + boughtPhones;
document.getElementById("masks").innerHTML = "Amount of phone masks: " + boughtMasks;
}
checkOptions();
function checkOptions(){
var check = prompt("There is three different ways to buy a phone. (A)utomatically, (M)anually and by (Q)uantity. Choose one option.")
if(check == "A"){
buyPhoneA();
}
else if(check == "M"){
buyPhoneM();
}
else if(check == "Q"){
buyPhoneQ();
}
else{
alert("That's not a valid option!");
}
}
function buyPhoneA(){
alert("With this option you automatically spend all your money ($" + bankBalance.toFixed(2) + ") and buy all available phones and phone masks! (take in notice that you can't buy one if you don't have money for the other!)");
var check = prompt("Type I AGREE if you agree to use this option!");
if(check == "I AGREE" && aPhones >= 1 && aMasks >= 1 && bankBalance >= 200.00){
while(bankBalance >= PHONE_PRICE + MASK_PRICE){
aPhones--;
aMasks--;
boughtPhones++;
boughtMasks++;
bankBalance = bankBalance - PHONE_PRICE - MASK_PRICE;
updateData();
var check = false;
}
}
else{
alert("Something went wrong! Either you didn't type I AGREE correctly, we don't have phones left or you don't have enough money!");
console.log(aPhones + " phones left");
console.log(aMasks + " masks left!");
console.log(boughtMasks + " bought masks!");
console.log(boughtPhones + " bought phones!");
console.log(bankBalance + " money left in the bank");
checkOptions();
}
}
function buyPhoneM(){
alert("With this options we will ask your over and over again to buy a phone! You can decline or agree to buying a new one! No accessories included");
var check = prompt("Type I AGREE if you agree to do this option!");
if(check == "I AGREE" && bankBalance >= 150.00 && aPhones >= 1){
aPhones--;
boughtPhones++;
bankBalance = bankBalance - PHONE_PRICE;
updateData();
buyPhoneM();
var check = false;
}
else{
alert("Something went wrong! Either you didn't type I AGREE correctly, we don't have any phones left or you don't have enough money!");
checkOptions();
}
}
function buyPhoneQ(){
var quantity = 0;
alert("With this option you will be asked to input a number of phones and accessories you want to buy!");
var check = prompt("Type I AGREE if you agree to use this option!");
if(check == "I AGREE"){
var quantity = prompt("Input a number of how many phones and accessories you want to buy!")
if(bankBalance >= 200.00 && aPhones >= 1 && aMasks >= 1){
aPhones + aPhones - quantity;
aMasks = aMasks - quantity;
bankBalance = bankBalance - ((PHONE_PRICE + MASK_PRICE) * 2);
boughtPhones = boughtPhones + quantity;
boughtMasks = boughtMasks + quantity;
updateData();
var check = false;
}
else{
alert("Something went wrong! Either the message your typed is not a number, you don't have enough money, we don't have enough masks or phones!");
buyPhoneQ();
}
}
}
HTML:
<html>
<head>
<link rel="stylesheet" type="text/css" href="main.css">
</head>
<body>
<p id="money">Money left: $1800</p>
<p id="phones">Amount of phones: 0</p>
<p id="masks">Amount of phone masks: 0</p>
<br><br>
<button onclick="eraseData();">Erase Data</button>
<script type="text/javascript" src="script.js"></script>
</body>
CSS's not really important for this..
(I don't remember why exactly put script tags below my button tag but I think it's because of something weird happening with my code, it didn't work until I did it that way )
I'd be grateful if anyone could help, thanks!
You have used global variable and local variables name same.
Either rename the function variable different from global variables or remove var ahead of function variable.

Compare generated letter with user input

My problem is as followed: I want to realise a (really) small application in which I want to generate a letter (between A and E) and compare it with the user input made afterwards. If the user input is not the same as the generated letter a message should pop up, which tells the user that he made the wrong choice. If the user made the right choice, a counter gets +1 and if the user reaches at least 3 of 5 points, he wins a prize. The user has 3 tries before the script ends.
The hurdle is that my main focus lies on php. My knowledge in JavaScript is not that much.
So my script won't do anything when the user types his answer in.
SOLVED!
The Code beneath is the solution.
String.prototype.last = function(){
return this[this.length - 1]
}
;(function() {
var score = 0;
var text = "";
var possible = "ABCDE";
var noOfTries = 5;
function generateCharacter() {
var index = Math.floor(Math.random() * 100) % possible.length;
text = possible[index];
possible = possible.slice(0, index) + possible.slice(index+1);
alert(text);
return text;
}
function validate(string) {
return (string || "").trim().last() === text.last();
}
function handleChange(){
var valid = validate(this.value);
if(valid){
score++;
alert("Richtig!");
}else{
alert("Das war leider falsch. Die richtige Antwort wäre " + text + " gewesen!");
}
console.log(this.value.length === noOfTries)
this.value.length === noOfTries ? notify() : generateCharacter();
}
function notify(){
if(score == 0) {
alert("Schade! Sie haben " + score + " Punkte erreicht! Nochmal?");
}else if(score >= 1 && score <3){
alert("Schade! Sie haben lediglich " + score + " von 5 Punkten erreicht! Nochmal?");
}else if(score >= 3 && score <= 5) {
alert("Herzlichen Glückwunsch! Sie haben " + score + " von 5 Punkten erreicht!");
}
}
function registerEvent(){
document.getElementById('which').addEventListener('keyup', handleChange);
}
registerEvent();
generateCharacter();
})()
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<label for="which">Antwort? </label>
<input type="text" name="which" id="which" placeholder="#" style="width: 9px;">
And here's the fiddle: Compare generated string with user input

Verify ID Number using javascript

I am trying to verify the south african ID NUMBER. I am not fluent with javascript.
I have the following code:
The HTML and Javascript
<html>
<head>
<script src="jquery-1.12.0.min.js"></script>
<title>the man</title>
<script>
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);
</script>
</head>
The Body:
<body>
<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>
</body>
</html>
Unfortunately I am not getting any error output. Please Assist
If this is the entire code, you are missing the closing head tag after script, I ran it and it worked as far as displaying different error messages with that cleaned up.
Edit- also added compiled code below which has document.ready shorthand.
<!DOCTYPE html>
<head>
<title>the man</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script>
$(function() {
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);
});
</script>
</head>
<body>
<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>
</body>
</html>
There were two proposed solutions and both of them would work.
First to remove script from the head section. (I guess you both placed </head> in different places, and that's why for one of you the submit attached correctly but not for the other)
<HTML>
<head>
<title>the man</title>
</head>
<body>
<script src="jquery-1.12.0.min.js"></script>
<script> //your code</script>
<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>
</body>
</html>
And the other to wrap all your code in
$(document).ready(wrapper);
function wrapper(){
function Validate() {
//your code
return false;
}
function isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
$('#idCheck').submit(Validate);
}
Why does the first solution work? First we render <head> so when your code is run
$('#idCheck').submit(Validate);
cannot be attached because the dom element does not exist yet. If we place the code in the execution is delayed.
Why does the second solution work? We wait until all page is rendered; only then do we execute our function that contains the same event attachment ($('#idCheck').submit(Validate);).

Categories

Resources