I wrote this code to validate credit card digits, saved it as an html file. It's not working though.
<html>
<head>
<script>
function mod10_check(val){
var nondigits = new RegExp(/[^0-9]+/g);
var number = val.replace(nondigits,'');
var pos, digit, i, sub_total, sum = 0;
var strlen = number.length;
if(strlen < 13){ return false; }
for(i=0;i
<strlen;i++){
pos = strlen - i;
digit = parseInt(number.substring(pos - 1, pos));
if(i % 2 == 1){
sub_total = digit * 2;
if(sub_total > 9){
sub_total = 1 + (sub_total - 10);
}
} else {
sub_total = digit;
}
sum += sub_total;
}
if(sum > 0 && sum % 10 == 0){
return true;
}
return false;
}
</script>
</head>
<body>
<form>
<input type="text"
name="cc_number"
onblur="if(mod10_check(this.value)){$('#cc_error').hide(); } else { $('#cc_error').show(); }"
value="" />
<span id="cc_er`enter code here`ror" style="display:none;">The card number is invalid.</span>
</form>
</body>
</html>
Does not validate value entered in the textbox. When the textbox goes out of focus message is not shown.Not willing to use any third party plugin.What is wrong with this code?
Try re-writing your inline code as an event handler.
var ccInp = document.getElementById('cc_no');
ccInp.addEventListener('blur', function() {
if(!mod10_check(ccInp.value)) {
document.getElementById('cc_error').style.display = '';
}
});
function mod10_check(val){
var nondigits = new RegExp(/[^0-9]+/g);
var number = val.replace(nondigits,'');
var pos, digit, i, sub_total, sum = 0;
var strlen = number.length;
if(strlen < 13){ return false; }
for(i=0;i
<strlen;i++){
pos = strlen - i;
digit = parseInt(number.substring(pos - 1, pos));
if(i % 2 == 1){
sub_total = digit * 2;
if(sub_total > 9){
sub_total = 1 + (sub_total - 10);
}
} else {
sub_total = digit;
}
sum += sub_total;
}
if(sum > 0 && sum % 10 == 0){
return true;
}
return false;
}
<form>
<input type="text"
name="cc_number"
value=""
id="cc_no"/>
<span id="cc_error" style="display:none;">The card number is invalid.</span>
</form>
jsFiddle: http://jsfiddle.net/8kyhtny2/
Related
Problem:
I am attempting to create an If Else statement, that when the user enters an incorrect value, outside of the range 0 to 80, it alerts the user to input a correct number.
It performs the equation the way I want it to, but when I purposefully input incorrect values, an alert does not appear and the program continues to answer the equation as if nothing ever happened.
The Code:
'use strict';
function calculate() {
var regPay;
var regHours = document.getElementById('regHours').value;
var hourlyRate = document.getElementById('hourlyRate').value;
if (regHours > 0 || regHours < 80) {
regPay = regHours * hourlyRate;
document.getElementById('regPay').value = regPay;
regPay = regPay.toFixed(2);
} else if (regHours < 0 || regHours > 80) {
alert("Enter valid number");
return false;
}
return false;
}
function init() {
document.getElementById('theForm').onsubmit = calculate;
}
window.onload = init;
label {
font-family : Arial, Helvetica, sans-serif;
font-size : 14px;
display : inline-block;
width : 10em;
}
div {
margin : .2em;
}
<form action="#" method="post" id="theForm">
<fieldset>
<legend>Payroll Calculator, find out how much you make!</legend>
<div>
<label for="regHours">Hours Worked (Between 0 and 80)</label>
<input type="text" name="regHours" id="regHours" value="0" required>
</div>
<div>
<label for="hourlyRate">Hourly Rate</label>
<input type="text" name="hourlyRate" id="hourlyRate" value="0.00" required>
</div>
<div>
<label for="regPay">Regular Pay</label>
<input type="text" name="regPay" id="regPay" value="0.00">
</div>
<div>
<input type="submit" value="Calculate" id="submit">
</div>
</fieldset>
</form>
I would write it this way
function calculate() {
'use strict';
var regPay;
var regHours = document.getElementById('regHours').value;
var hourlyRate = document.getElementById('hourlyRate').value;
if (regHours > 0 || regHours < 80) {
regPay = regHours * hourlyRate;
document.getElementById('regPay').value = regPay;
regPay = regPay.toFixed(2);
return true
}
alert ("Enter valid number");
return false;
}
you also need to validate that regHours and hourlyRate hold valid numeric values.
your if condition
if (regHours > 0 || regHours < 80)
is always true
did you mean
if (regHours > 0 && regHours < 80)
After some digging and experimenting, and help from the answers I have found a solution to my problem. I figured I'd add it here (this was the complete end result and the part I was having trouble with was the if then for less than 80):
/*global document: false */
/*jslint devel: true */
function calculate() {
'use strict';
// Input variables
var firstName = document.getElementById('firstName').value,
lastName = document.getElementById('lastName').value,
totHours =
parseFloat(document.getElementById('totHours').value),
regHours = parseFloat(document.getElementById('regHours').value),
overHours = document.getElementById('overHours').value,
hourlyRate = parseFloat(document.getElementById('hourlyRate').value),
fica = document.getElementById('fica').value,
stateTax = document.getElementById('stateTax').value,
fedTax = document.getElementById('fedTax').value;
// Enter in a valid rate
if ((totHours < 0 || totHours > 80) && (hourlyRate < 0 || hourlyRate > 100.0)) {
alert("Please enter valid hours and a valid payrate!");
document.getElementById("theForm").reset("theForm");
} else if (totHours < 0 || totHours > 80) {
//return false;
alert("Please Input valid hours");
document.getElementById("theForm").reset("theForm");
} else if (hourlyRate < 0 || hourlyRate > 100.0) {
alert("Please Input valid hourly rate");
document.getElementById("theForm").reset("theForm");
} else {
//valid
}
// For calculations
if (totHours > 40) {
overHours = 0;
overHours += (totHours - 40);
regHours = 40;
} else if (totHours <= 40) {
regHours = totHours;
}
document.getElementById('regHours').value = regHours;
document.getElementById('overHours').value = overHours;
if (totHours <= 40) {
document.getElementById('regHours').value = regHours;
}
var regPay = (hourlyRate * regHours).toFixed(2),
overtimePay = (overHours * (1.5 * hourlyRate)).toFixed(2),
grossPay = parseFloat(+regPay + +overtimePay).toFixed(2),
totalTax = (parseFloat(+fica + +stateTax + +fedTax) / 100 * grossPay).toFixed(2),
netPay = (grossPay - totalTax).toFixed(2),
employeeName = firstName + " " + lastName;
// output values
document.getElementById('regPay').value = regPay;
document.getElementById('overtimePay').value = overtimePay;
document.getElementById('grossPay').value = grossPay;
document.getElementById('totalTax').value = totalTax;
document.getElementById('employeeName').value = employeeName;
document.getElementById('netPay').value = netPay;
return false;
}
function init() {
'use strict';
document.getElementById('theForm').onsubmit = calculate;
}
window.onload = init;
My mortgage calculator includes a down payment field for either a value or a percentage.
If the user enters a value, the percentage is calculated and displayed. If the user enters a percentage, the value is calculated and displayed.
The problem I am having is that once entered, only the value can be modified, not the percentage.
The relevant code is
var Vdown = document.calc.downPayment.value;
if (Vdown == 0 || Vdown == "") {
Vdown = 0;
} else {
var result = (Vdown / VappraisedValue) * 100;
document.calc.downPaymentPercent.value = result;
document.calc.downPayment.value = Vdown;
}
var VdownPercent = document.calc.downPaymentPercent.value;
if (VdownPercent == 0 || VdownPercent == "") {
VdownPercent = 0;
} else {
var percent = (VdownPercent / 100) * VappraisedValue;
document.calc.downPayment.value = percent.toFixed(0);
document.calc.downPaymentPercent.value = VdownPercent;
}
Please see my jsfiddle
function fn(num, places, comma) {
var isNeg = 0;
if (num < 0) {
num = num * -1;
isNeg = 1;
}
var myDecFact = 1;
var myPlaces = 0;
var myZeros = "";
while (myPlaces < places) {
myDecFact = myDecFact * 10;
myPlaces = Number(myPlaces) + Number(1);
myZeros = myZeros + "0";
}
onum = Math.round(num * myDecFact) / myDecFact;
integer = Math.floor(onum);
if (Math.ceil(onum) == integer) {
decimal = myZeros;
} else {
decimal = Math.round((onum - integer) * myDecFact)
}
decimal = decimal.toString();
if (decimal.length < places) {
fillZeroes = places - decimal.length;
for (z = 0; z < fillZeroes; z++) {
decimal = "0" + decimal;
}
}
if (places > 0) {
decimal = "." + decimal;
}
if (comma == 1) {
integer = integer.toString();
var tmpnum = "";
var tmpinteger = "";
var y = 0;
for (x = integer.length; x > 0; x--) {
tmpnum = tmpnum + integer.charAt(x - 1);
y = y + 1;
if (y == 3 & x > 1) {
tmpnum = tmpnum + ",";
y = 0;
}
}
for (x = tmpnum.length; x > 0; x--) {
tmpinteger = tmpinteger + tmpnum.charAt(x - 1);
}
finNum = tmpinteger + "" + decimal;
} else {
finNum = integer + "" + decimal;
}
if (isNeg == 1) {
finNum = "-" + finNum;
}
return finNum;
}
function sn(num) {
num = num.toString();
var len = num.length;
var rnum = "";
var test = "";
var j = 0;
var b = num.substring(0, 1);
if (b == "-") {
rnum = "-";
}
for (i = 0; i <= len; i++) {
b = num.substring(i, i + 1);
if (b == "0" || b == "1" || b == "2" || b == "3" || b == "4" || b == "5" || b == "6" || b == "7" || b == "8" || b == "9" || b == ".") {
rnum = rnum + "" + b;
}
}
if (rnum == "" || rnum == "-") {
rnum = 0;
}
rnum = Number(rnum);
return rnum;
}
function computeForm(form) {
var VappraisedValue = document.calc.appraisedValue.value;
var Vdown = document.calc.downPayment.value;
if (Vdown == 0 || Vdown == "") {
Vdown = 0;
} else {
var result = (Vdown / VappraisedValue) * 100;
document.calc.downPaymentPercent.value = result;
document.calc.downPayment.value = Vdown;
}
var VdownPercent = document.calc.downPaymentPercent.value;
if (VdownPercent == 0 || VdownPercent == "") {
VdownPercent = 0;
} else {
var percent = (VdownPercent / 100) * VappraisedValue;
document.calc.downPayment.value = percent.toFixed(0);
document.calc.downPaymentPercent.value = VdownPercent;
}
}
<form name="calc" method="post" action="#">
<table border='1' cellpadding='4' cellspacing='0'>
<tbody>
<tr>
<td nowrap>
Home value:
</td>
<td align="center">
<span class="input-group-addon">$</span>
<input id="appraised-value" type="number" min="0" max="10000000" step="25000" class="form-control" name="appraisedValue" onKeyUp="computeForm(this.form)" value="0" onfocus="if(this.value==this.defaultValue)this.value=''" onblur="if(this.value=='')this.value=this.defaultValue">
</td>
</tr>
<tr>
<td nowrap>
Down payment:
</td>
<td align="center">
<span class="input-group-addon">$</span>
<input id="down-payment" type="number" min="0" max="10000000" step="5000" class="form-control" name="downPayment" onKeyUp="computeForm(this.form)" value="0" onfocus="if(this.value==this.defaultValue)this.value=''">
<input id="down-payment-percent" type="number" min="0" max="100" step="1" class="form-control" name="downPaymentPercent" onKeyUp="computeForm(this.form)" value="0" onfocus="if(this.value==this.defaultValue)this.value=''">
<span class="input-group-addon">%</span>
</td>
</tr>
</tbody>
</table>
</form>
The issue is the way you are updating the Payment / Percent values - every time either value is updated, the code in computeForm uses the value in Payment to update Percent, and only then the value of Percent (just updated) is used to set Payment. As a result, whatever is in Payment will always win.
A couple of options to get it working the way you want it to:
You could pass a variable in the "onKeyUp" events of Payment and Percent that tells ComputeForm which to use to update the other, using an if(which === "pmt") { [code_to_update_payment] } else { [code_to_update_pct] } type construct.
You could break out the update code into two separate functions, function updatePmt() { } function updatePct() { } and then call each from the respective "onKeyUp" method in the HTML.
Either should work equally well to solve the behavior you are experiencing.
I have a javascript variable with parameters, but I don't know how to pass it into my html code. The javascript code is taken from https://gist.github.com/EvanHahn/2587465:
var caesarShift = function(str, amount) {
// Wrap the amount
if (amount < 0)
return caesarShift(str, amount + 26);
// Make an output variable
var output = '';
// Go through each character
for (var i = 0; i < str.length; i ++) {
// Get the character we'll be appending
var c = str[i];
// If it's a letter...
if (c.match(/[a-z]/i)) {
// Get its code
var code = str.charCodeAt(i);
// Uppercase letters
if ((code >= 65) && (code <= 90))
c = String.fromCharCode(((code - 65 + amount) % 26) + 65);
// Lowercase letters
else if ((code >= 97) && (code <= 122))
c = String.fromCharCode(((code - 97 + amount) % 26) + 97);
}
// Append
output += c;
}
// All done!
return output;
};
I want to pass it on to my HTML obviously. I have done some research, and have come across ways such as:
<p id="output"></p>
and then
document.getElementById('output').innerHTML = lengthOfName;
but I don't know how to add it all together. How do I call the variable? For the string, I have a text area input box, and maybe a clicker for the second argument, the amount, but I don't know how to put it all together in the HTML.
You'll need to up the JavaScript inside a script tag and the p tag that you are getting by id in the body of an html document, like so:
<!DOCTYPE html>
<html>
<head>
<title>Page</title>
</head>
<body>
<form id="form">
<div>
<label for="str">String:</label>
<input id="str" />
</div>
<div>
<label for="amount">Amount:</label>
<input id="amount" />
</div>
<button type="submit">Submit</button>
</form>
<p>CaesarShift: <span id="output"></span></p>
<script>
var caesarShift = function (str, amount) {
// Wrap the amount
if (amount < 0) return caesarShift(str, amount + 26);
// Make an output variable
var output = "";
// Go through each character
for (var i = 0; i < str.length; i++) {
// Get the character we'll be appending
var c = str[i];
// If it's a letter...
if (c.match(/[a-z]/i)) {
// Get its code
var code = str.charCodeAt(i);
// Uppercase letters
if (code >= 65 && code <= 90)
c = String.fromCharCode(((code - 65 + amount) % 26) + 65);
// Lowercase letters
else if (code >= 97 && code <= 122)
c = String.fromCharCode(((code - 97 + amount) % 26) + 97);
}
// Append
output += c;
}
// All done!
return output;
};
const form = document.getElementById("form");
form.addEventListener("submit", handleSubmit);
function handleSubmit(event) {
event.preventDefault();
let str = document.getElementById("str").value;
let amount = parseInt(document.getElementById("amount").value);
let output = document.getElementById("output");
console.log(amount);
if (!amount) {
output.innerHTML = `<span style="color: red">Amount not valid</span>`;
return;
}
output.innerHTML = caesarShift(str, parseInt(amount));
}
</script>
</body>
</html>
See the snippet below with a working example:
var caesarShift = function(str, amount) {
// Wrap the amount
if (amount < 0) return caesarShift(str, amount + 26);
// Make an output variable
var output = "";
// Go through each character
for (var i = 0; i < str.length; i++) {
// Get the character we'll be appending
var c = str[i];
// If it's a letter...
if (c.match(/[a-z]/i)) {
// Get its code
var code = str.charCodeAt(i);
// Uppercase letters
if (code >= 65 && code <= 90)
c = String.fromCharCode(((code - 65 + amount) % 26) + 65);
// Lowercase letters
else if (code >= 97 && code <= 122)
c = String.fromCharCode(((code - 97 + amount) % 26) + 97);
}
// Append
output += c;
}
// All done!
return output;
};
const handleSubmit = (e) => e.preventDefault();
const updateResult = () => {
amount = parseInt(document.getElementById("amount").value);
let output = document.getElementById("output");
if (!amount) {
output.innerHTML = `<span style="color: red">Amount not valid</span>`;
return;
}
output.innerHTML = caesarShift(
document.getElementById("text").value,
parseInt(amount)
);
};
const form = document.getElementById("form");
form.addEventListener("submit", handleSubmit);
let text = document.getElementById("text");
text.addEventListener("keyup", updateResult);
text.addEventListener("blur", updateResult);
let amount = document.getElementById("amount");
amount.addEventListener("change", updateResult);
amount.addEventListener("blur", updateResult);
<form id="form">
<div>
<label for="text">Text:</label>
<textarea id="text"></textarea>
</div>
<div>
<label for="amount">Amount:</label>
<input id="amount" />
</div>
</form>
<p>CaesarShift: <span id="output"></span></p>
I am trying to get javascript to format phone numbers based on a users input of 10 or 11 digits. The 11 digits are for phone numbers that start with a 1 at the beginning like a 1-800 number. I need the final output to be either 000-000-0000 or 1-000-000-0000. The sample javascript code that I was given to start out with, works with the 10 digit phone number but I need the javascript to also recognize if there is a 1800 number and append accordingly.
The following is my initial working javascript and below that is code I found online that addresses the 10 and 11 digital formatting however I don’t know how to mesh the two together.
Thank you in advance for any help given.
~~~~~~~~~~~~~~~~~
<script type="text/javascript">
var phoneNumberVars = [ "UserProfilePhone", "UserProfilePhone1", "UserProfilePhone2", "UserProfilePhone3", ];
InitialFormatTelephone();
function InitialFormatTelephone()
{
for (var i = 0; i < phoneNumberVars.length; i++)
{
FormatTelephone(phoneNumberVars[i]);
}
}
function StorefrontEvaluateFieldsHook(field)
{
for (var i = 0; i < phoneNumberVars.length; i++)
{
if (field.id == "FIELD_" + FieldIDs[phoneNumberVars[i]])
{
FormatTelephone(phoneNumberVars[i]);
}
}
}
function FormatTelephone(varName)
{
var num = document.getElementById("FIELD_" + FieldIDs[varName]).value;
var charArray = num.split("");
var digitCounter = 0;
var formattedNum;
if (charArray.length > 0)
formattedNum = “-“;
else
formattedNum = "";
var i;
for (i = 0;i < charArray.length; i++)
{
if (isDigit(charArray[i]))
{
formattedNum = formattedNum + charArray[i];
digitCounter++;
if (digitCounter == 3)
{
formattedNum = formattedNum + “-“;
}
if (digitCounter == 6)
{
formattedNum = formattedNum + "-";
}
}
}
if (digitCounter != 0 && digitCounter != 10)
{
alert ("Enter a valid phone number!");
}
// now that we have a formatted version of the user's phone number, replace the field with this new value
document.getElementById("FIELD_" + FieldIDs[varName]).value = formattedNum;
// force an update of the preview
PFSF_AjaxUpdateForm();
}
function isDigit(aChar)
{
myCharCode = aChar.charCodeAt(0);
if((myCharCode > 47) && (myCharCode < 58))
{
return true;
}
return false;
}
</script>
<script type="text/javascript">
var phoneNumberVars = [ "UserProfilePhone", "UserProfilePhone1", "UserProfilePhone2", "UserProfilePhone3", ];
InitialFormatTelephone();
function InitialFormatTelephone()
{
for (var i = 0; i < phoneNumberVars.length; i++)
{
FormatTelephone(phoneNumberVars[i]);
}
}
function StorefrontEvaluateFieldsHook(field)
{
for (var i = 0; i < phoneNumberVars.length; i++)
{
if (field.id == "FIELD_" + FieldIDs[phoneNumberVars[i]])
{
FormatTelephone(phoneNumberVars[i]);
}
}
}
function FormatTelephone(varName)
{
var num = document.getElementById("FIELD_" + FieldIDs[varName]).value;
var cleanednum = num.replace( /[^0-9]/g, "");
var charArray = cleanednum.split("");
var digitCounter = 0;
var formattedNum = "";
var digitPos1 = 0;
var digitPos3 = 3;
var digitPos6 = 6;
if (charArray.length ===11)
{
digitPos1++;
digitPos3++;
digitPos6++;
}
if (charArray.length > 0)
formattedNum = "";
else
formattedNum = "";
var i;
for (i = 0;i < charArray.length; i++)
{
if (isDigit(charArray[i]))
{
formattedNum = formattedNum + charArray[i];
digitCounter++;
if (digitCounter === digitPos1)
{
formattedNum = formattedNum + "-";
}
if (digitCounter == digitPos3)
{
formattedNum = formattedNum + "-";
}
if (digitCounter == digitPos6)
{
formattedNum = formattedNum + "-";
}
}
}
if ((charArray.length ==10 || charArray.length == 11 || charArray.length == 0) === false)
{
alert ("Enter a valid phone number!");
}
// now that we have a formatted version of the user's phone number, replace the field with this new value
document.getElementById("FIELD_" + FieldIDs[varName]).value = formattedNum;
// force an update of the preview
PFSF_AjaxUpdateForm();
}
function isDigit(aChar)
{
myCharCode = aChar.charCodeAt(0);
if((myCharCode > 47) && (myCharCode < 58))
{
return true;
}
return false;
}
</script>
I'm trying to find whether or a not a number is a perfect number, but I can't get it to print right. The numbers 6, 496, 8128 are perfect numbers but when I entered those it kept printing from var res2 instead of var res1. What's the problem here, can anyone can help?
function perfectNo(number) {
var temp = 0;
var res1 = "It is a perfect number";
var res2 = "It is not a perfect number";
for (var i = 1; i <= number / 2; i++) {
if (number % i == 0) {
temp += i;
}
}
if (temp == number && temp != 0) {
document.getElementById("results").innerHTML = res1;
} else {
document.getElementById("results").innerHTML = res2;
}
}
<input id="num">
<input type="button" onclick="perfectNo()" value="check">
<br>
<p>Answer:</p>
<p id="results"></p>
<br>
Try with :
var number = document.getElementById("num").value;
Like this :
function perfectNo() {
var number = document.getElementById("num").value;
console.log(number);
var temp = 0;
var res1 = "It is a perfect number";
var res2 = "It is not a perfect number";
for (var i = 1; i <= number / 2; i++) {
if (number % i == 0) {
temp += i;
}
}
if (temp == number && temp != 0) {
document.getElementById("results").innerHTML = res1;
} else {
document.getElementById("results").innerHTML = res2;
}
}
<input id="num">
<input type="button" onclick="perfectNo()" value="check">
<br>
<p>Answer:</p>
<p id="results"></p>
<br>