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.
Related
I want to make a slider go from 1-999 stepping by 1, then from 1k to 5m stepping 1k, looking like this
1 2 3------999|1k-2k-3k----999k|1m-2m---5m
I have a code setup that goes from 1k to 5m, I want to add from 1 to 999 in a nice way at the start of the slider, but I cant make it.
<div class="form-group">
<div class="wrapper">
<h5 class="font-alt mt-30">Number of Followers</h5>
<div class="price-input">
<div class="field">
<input readonly
class="input-min" value="0"
name="followers-min">
</div>
<div class="separator">-</div>
<div class="field">
<input readonly
class="input-max" value="INFINITY"
name="followers-max">
</div>
</div>
<div class="slider">
<div class="progress"></div>
</div>
<div class="range-input">
<input style="cursor: pointer;" type="range" class="range-min" min="0"
max="5000000"
value="0"
step="1000">
<input style="cursor: pointer;" type="range" class="range-max" min="0"
max="5000000"
value="5000000"
step="1000">
</div>
</div>
</div>
My current javascript
const rangeInput = document.querySelectorAll(".range-input input"),
priceInput = document.querySelectorAll(".price-input input"),
range = document.querySelectorAll(".slider .progress");
let priceGap = 100_000;
rangeInput.forEach(input => {
input.addEventListener("input", e => {
let minVal = parseInt(rangeInput[0].value),
maxVal = parseInt(rangeInput[1].value);
if ((maxVal - minVal) < priceGap) {
if (e.target.className === "range-min") {
rangeInput[0].value = maxVal - priceGap
} else {
rangeInput[1].value = minVal + priceGap;
}
} else {
let temp = 0
let addition = ""
if (minVal < 1_000) {
temp = String(minVal)
} else if (minVal >= 1_000 && minVal < 10_000) {
temp = String(minVal)[0]
addition = "K"
} else if (minVal >= 10_000 && minVal < 100_000) {
temp = String(minVal)[0] + String(minVal)[1]
addition = "K"
} else if (minVal >= 100_000 && minVal < 1_000_000) {
temp = String(minVal)[0] + String(minVal)[1] + String(minVal)[2]
addition = "K"
} else if (minVal >= 1_000_000) {
temp = String(minVal)[0]
addition = "M"
}
let tempMax = 0
let additionMax = ""
if (maxVal >= 1_000 && maxVal < 10_000) {
tempMax = String(maxVal)[0]
additionMax = "K"
} else if (maxVal >= 10_000 && maxVal < 100_000) {
tempMax = String(maxVal)[0] + String(maxVal)[1]
additionMax = "K"
} else if (maxVal >= 100_000 && maxVal < 1_000_000) {
tempMax = String(maxVal)[0] + String(maxVal)[1] + String(maxVal)[2]
additionMax = "K"
} else if (maxVal >= 1_000_000) {
tempMax = String(maxVal)[0]
additionMax = "M"
}
if (maxVal === 5000000) {
priceInput[1].value = "INFINITY";
} else {
priceInput[1].value = Number(tempMax) + additionMax;
}
priceInput[0].value = Number(temp) + addition;
range[0].style.left = ((minVal / rangeInput[0].max) * 100) + "%";
range[0].style.right = 100 - (maxVal / rangeInput[1].max) * 100 + "%";
}
}
)
;
});
Any idea on how to add from 1-999 at the first of the slider so that it looks a bit like the slider on that website?
https://inflact.com/tools/instagram-search/
You can conditionally adjust the step attribute depending on the current value.
const slider = document.querySelector("#slider");
const output = document.querySelector("output");
slider.addEventListener("input", (e) => {
const value = e.target.value;
if (value < 2500) {
slider.setAttribute("step", 1);
}
else if (value >= 2500 && value < 5000) {
slider.setAttribute("step", 100);
}
else if (value >= 5000) {
slider.setAttribute("step", 500);
}
output.value = e.target.value;
});
<main>
<label for="slider">Slider</label>
<input type="range" name="slider" id="slider" value="0" min="0" max="10000" step="1">
<output name="output" for="slider">0</output>
</main>
As the title says I am trying to write luhns algorithm in Javascript and have it print out a valid card number and what type of card it is whether that be American Express, Mastercard, or Visa.
When ran all it does is continuously loop the alert box. What I want it to print is this is a valid card type and what brand of card it is in the Alert Box.
function checkCreditCard() {
var ccnum = document.getElementById("cardnum").value;
var cardArray = [cardnum]
var temp = ccnum;
var checkerArray;
if (cardType(ccnum) === "AmericanExpress") {
checkerArray = [15];
for (x = 0; x < 15; x++) {
checkerArray[x] = ccnum % 10;
ccnum = ccnum / 10;
}
} else {
checkerArray = [16];
for (x = 0; x < 16; x++) {
checkerArray[x] = ccnum % 10;
ccnum = ccnum / 10;
if (ccnum == 0) {
checkerArray[15] = -1;
checkerArray[14] = -1;
checkerArray[13] = -1;
}
}
}
var summing;
for (x = 1; x < checkerArray.length; x = x + 2) {
if (checkerArray[x] < 0) {
return;
}
checkerArray[x] = checkerArray[x] * 2;
if (checkerArray[x] >= 10) {
summing = summing + checkerArray[x] % 10 + checkerArray[x] / 10
} else {
summing = summing + checkerArray[x];
}
}
for (x = 0; x < checkerArray.length; x = x + 2) {
if (checkerArray[x] < 0) {
return;
}
summing = summing + checkerArray[x];
if (summing == 20) {
alert("This Card is Legit")
} else {
alert("This Card is Invalid")
}
}
function cardType(ccnum) {
var x = {
Visa: /^4[0-9]{12}(?:[0-9]{3})?$/,
Mastercard: /^5[1-5][0-9]{14}$/,
AmericanExpress: /^3[47][0-9]{13}$/,
}
for (var l in x) {
if (x[l].test(ccnum)) {
return l;
}
}
return null;
}
}
<input type="text" id="cardnum" onkeyup="checkCreditCard()" />
<span id="valid">Enter a Number and Press Enter</span>
Let's use let
Also let's move the alert OUTSIDE the loop
function cardType(ccnum) {
var x = {
Visa: /^4[0-9]{12}(?:[0-9]{3})?$/,
Mastercard: /^5[1-5][0-9]{14}$/,
AmericanExpress: /^3[47][0-9]{13}$/,
}
for (var l in x) {
if (x[l].test(ccnum)) {
return l;
}
}
return null;
}
document.getElementById("cardForm").addEventListener("submit", function(e) {
e.preventDefault();
var ccnum = document.getElementById("cardnum").value;
if (ccnum.length < 16) return
var cardArray = [cardnum]
var temp = ccnum;
var checkerArray;
if (cardType(ccnum) === "AmericanExpress") {
checkerArray = [15];
for (let x = 0; x < 15; x++) {
checkerArray[x] = ccnum % 10;
ccnum /= 10;
}
} else {
checkerArray = [16];
for (let x = 0; x < 16; x++) {
checkerArray[x] = ccnum % 10;
ccnum /= 10;
if (ccnum == 0) {
checkerArray[15] = -1;
checkerArray[14] = -1;
checkerArray[13] = -1;
}
}
}
var summing;
for (let x = 1; x < checkerArray.length; x = x + 2) {
checkerArray[x] *= 2;
if (checkerArray[x] >= 10) {
summing += checkerArray[x] % 10 + checkerArray[x] / 10
} else {
summing += checkerArray[x];
}
}
for (let x = 0; x < checkerArray.length; x = x + 2) {
summing += checkerArray[x];
}
if (summing == 20) {
alert("This Card is Legit")
} else {
alert("This Card is Invalid")
}
})
<form id="cardForm">
<input type="tel" id="cardnum" maxlength="16" />
<span id="valid">Enter a Number and Press Enter</span>
</form>
So whenever the moves variable is equal to 10 (why 10 and not 9? I dunno the moves variable increases 2 times instead of 1 the last time xD), the alert that the game is a draw does not happen and why's that?
I'm making a tic tac toe game by the way.
var moves = 0;
var randomOneTwo = doGetRandom(1,2)
var randomPlayBot = 0;
var turn = randomOneTwo == 1 ? "X": "O"
var score1 = 0;
var score2 = 0;
var win = 0;
var canPlay = false;
var dummy = score2;
var dummy2 = score1;
var whoWon = 5;
window.addEventListener("load", _loaded);
function _loaded() {
document.getElementById("plpl").textContent = "The Player " + turn + " is playing."
var ids = ['b1', 'b2', 'b3', 'b4', 'b5', 'b6', 'b7', 'b8', 'b9'];
var vale = [0, 0, 0, 0, 0, 0, 0, 0, 0 ,0];
for (var i = 0; i < ids.length; i++) {
document.getElementById(ids[i]).addEventListener("click", doSet);
}
addEventListener("click", bot);
addEventListener("click", doWin);
function doSet(){
if (this.innerHTML !== "") {
return;
}
this.innerHTML = turn;
moves++
canPlay = true;
turn == "X" ? turn = "O": turn = "X"
document.getElementById("plpl").textContent = "The Player " + turn + " is playing."
turn == "X" ? vale[nc] = 100: vale[nc] = -100;
}
function bot(){
if ((canPlay == true) && (document.getElementById("bplays").checked == true)) {
do{
randomPlayBot = doGetRandom(0, 8)
}
while(document.getElementById(ids[randomPlayBot]).innerHTML !== "" && moves < 8)
document.getElementById(ids[randomPlayBot]).innerHTML = turn;
moves++
turn == "X" ? turn = "O": turn = "X"
document.getElementById("plpl").textContent = "The Player " + turn + " is playing."
turn == "X" ? vale[randomPlayBot] = 100: vale[randomPlayBot] = -100;
canPlay = false;
}
}
function doWin(){
console.log(vale)
let sum1 = vale[0] + vale[1] + vale[2];
let sum2 = vale[3] + vale[4] + vale[5];
let sum3 = vale[6] + vale[7] + vale[8];
let sum4 = vale[0] + vale[3] + vale[6];
let sum5 = vale[1] + vale[4] + vale[7];
let sum6 = vale[2] + vale[5] + vale[8];
let sum7 = vale[0] + vale[4] + vale[8];
let sum8 = vale[2] + vale[4] + vale[6];
for (i = 0; i <= 8; i++) {
if ((sum1 == 300 || sum2 == 300 || sum3 == 300 || sum4 == 300 || sum5 == 300 || sum6 == 300 || sum7 == 300 || sum8 == 300)) {
whoWon = 1;
score2 == dummy ? score2++:
document.getElementById("sc1").innerHTML = "O: " + score2;
for (j = 0; j < ids.length; j++) {
document.getElementById(ids[j]).textContent = ""
}
canPlay = false;
moves = 0;
}
else if ((sum1 == -300 || sum2 == -300 || sum3 == -300 || sum4 == -300 || sum5 == -300 || sum6 == -300 || sum7 == -300 || sum8 == -300)) {
whoWon = -1;
score1 == dummy2 ? score1++:
document.getElementById("sc2").innerHTML = "X: " + score1;
for (j = 0; j < ids.length; j++) {
document.getElementById(ids[j]).textContent = ""
}
canPlay = false;
moves = 0;
}
else if(moves == 10){
whoWon = 0;
for (j = 0; j < ids.length; j++) {
document.getElementById(ids[j]).textContent = ""
}
canPlay = false;
moves = 0;
}
else{
return;
}
}
if (whoWon == 1) {
alert("The Player O won and so he gets 1 point!")
}
else if(whoWon == -1){
alert("The Player X won and so he gets 1 point!")
}
else if(whoWon == 0){
alert("It's a draw and so nobody won any points!");
}
whoWon = 5;
dummy = score2;
dummy2 = score1;
sum1 = 0;
sum2 = 0;
sum3 = 0;
sum4 = 0;
sum5 = 0;
sum6 = 0;
sum7 = 0;
sum8 = 0;
for(k = 0; k <= 8; k++){
vale[k] = 0;
}
}
}
function doGetRandom(min, max) {
let h = Math.random() * (max - min) + min;
return Math.round(h);
}
function doGetNum(n){
nc = n;
}
-------------------------------------------------------------//--------------------------------------------------------------------
Edit 1: Html
<h1 class="hd-1" id="plpl"></h1>
<table>
<tr>
<td id="sc1">O: 0</td>
<td id="sc2">X: 0</td>
</tr>
</table>
<table id="tb-ttt">
<tr>
<td class="td-ttt" id="b1" onclick="doGetNum('0')"></td>
<td class="td-ttt" id="b2" onclick="doGetNum('1')"></td>
<td class="td3-ttt" id="b3" onclick="doGetNum('2')"></td>
</tr>
<tr>
<td class="td-ttt" id="b4" onclick="doGetNum('3')"></td>
<td class="td-ttt" id="b5" onclick="doGetNum('4')"></td>
<td class="td3-ttt" id="b6" onclick="doGetNum('5')"></td>
</tr>
<tr>
<td class="td2-ttt" id="b7" onclick="doGetNum('6')"></td>
<td class="td2-ttt" id="b8" onclick="doGetNum('7')"></td>
<td class="td4-ttt" id="b9" onclick="doGetNum('8')"></td>
</tr>
</table>
<form name="F">
Player vs CPU <input type="radio" name="bot" value="" checked id="bplays">
Player vs Player <input type="radio" name="bot" value="" id="plvpl">
</form>
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>
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/