Input value always is equal 0 - javascript

I'm installing a calculation and I want to finalize it by using a special discount for each vehicle. if I use the input domnpayment function without checked checkboxes it always pops up that my downpayment greater than 95% due to variable finalVehiclePriceValue value is equal to 0 and downpayment in percent is Infinity, while variable finalVehiclePricePlusBuyBack has its own value. Where did I go wrong?
$(function() {
$('#priceVehicle').keyup(function() {
var str = $(this).val();
str = str.replace(/\D+/g, '');
$(this).val(str.replace(/\d(?=(?:\d{3})+(?!\d))/g, '$& '));
}); // end priceVehicle keyup
$("#downPayment").on('keyup', function() {
this.value = this.value.replace(/ /g, '');
var number = this.value;
this.value = number.replace(/\B(?=(\d{3})+(?!\d))/g, " ");
}); //end downPayment keyup
var vehicleFinanceValue = parseInt($("input[name=vehicleFinanceValue]").val().replace(/ /g, '')) || 0,
tradeInValue = parseInt($("input[name=tradeInValue]").val().replace(/ /g, '')) || 0,
buyBackValue = parseInt($("input[name=buyBackValue]").val().replace(/ /g, '')) || 0,
finalVehiclePriceValue = parseInt($("input[name=finalVehiclePriceValue]").val().replace(/ /g, '')) || 0,
finalVehiclePricePlusBuyBack = parseInt($("input[name=finalVehiclePricePlusBuyBack]").val().replace(/ /g, '')) || 0;
$("#listVehicle").change(function() {
var listVehicle = $(this).val();
vehicleFinanceValue = (listVehicle === "vehicleOne") ? 20000 :
(listVehicle === "vehicleTwo") ? 10000 : 0;
tradeInValue = (listVehicle === "vehicleOne") ? 20000 :
(listVehicle === "vehicleTwo") ? 10000 : 0;
buyBackValue = (listVehicle === "vehicleOne") ? 10000 :
(listVehicle === "vehicleTwo") ? 10000 : 0
console.log(vehicleFinanceValue);
$("#vehicleFinanceValue").val(vehicleFinanceValue);
$("#tradeInValue").val(tradeInValue);
$("#buyBackValue").val(buyBackValue);
}); // end change listVehicle
$("input[name=priceVehicle]").change(function() {
var vehiclePrice = parseInt($("input[name=priceVehicle]").val().replace(/ /g, '')) || 0,
finalVehiclePriceValue = vehiclePrice;
finalVehiclePricePlusBuyBack = vehiclePrice;
$("input[name=finalVehiclePriceValue]").val($(this).val());
$("input[name=finalVehiclePricePlusBuyBack]").val($(this).val());
$("#priceVehicle").val(vehiclePrice);
$("#finalVehiclePriceValue").val(finalVehiclePriceValue);
$("#finalVehiclePricePlusBuyBack").val(finalVehiclePricePlusBuyBack);
console.log(finalVehiclePriceValue);
console.log(finalVehiclePricePlusBuyBack);
}); // end priceVehicle change
$('.salesCheckboxes input[type="checkbox"]').change(function() {
var vehicleList = $("#listVehicle").val(),
vehiclePrice = parseInt($("input[name=priceVehicle]").val().replace(/ /g, '')) || 0,
vehicleFinance = $("input[name=vehicleFinance]"),
tradeIn = $("input[name=tradeIn]");
if (vehicleFinance.is(":checked") && vehicleList === "vehicleOne") {
finalVehiclePriceValue = (vehiclePrice - vehicleFinanceValue);
finalVehiclePricePlusBuyBack = (vehiclePrice - (vehicleFinanceValue + buyBackValue));
} else if (tradeIn.is(":checked") && vehicleList === "vehicleOne") {
finalVehiclePriceValue = (vehiclePrice - tradeInValue);
finalVehiclePricePlusBuyBack = (vehiclePrice - (vehicleFinanceValue + tradeInValue + buyBackValue));
} else {
finalVehiclePriceValue = vehiclePrice;
finalVehiclePricePlusBuyBack = vehiclePrice - buyBackValue;
}
$("#finalVehiclePriceValue").val(finalVehiclePriceValue.toLocaleString('ru-RU'));
$("#finalVehiclePricePlusBuyBack").val(finalVehiclePricePlusBuyBack.toLocaleString('ru-RU'));
console.log(finalVehiclePriceValue);
}); // end salesCheckboxes
$("input[name=downPayment").change(function() {
var downPayment = parseInt($("input[name=downPayment]").val().replace(/ /g, '')) || 0;
var downPaymentInPercent = parseInt($("input[name=downPaymentInPercent]").val());
downPaymentInPercent = Number(((downPayment / finalVehiclePriceValue) * 100).toFixed(2));
console.log(downPaymentInPercent);
console.log(finalVehiclePriceValue);
console.log(finalVehiclePricePlusBuyBack);
console.log(downPayment);
$("#downPaymentInPercent").val(downPaymentInPercent + "%");
$("#downPaymentValue").html(downPayment.toLocaleString('ru-RU'));
if (downPaymentInPercent < 10) {
alert("downpayment must be greater than 10%");
} else if (downPaymentInPercent > 95) {
alert("downpayment must not be greater than 95%");
}
}); // end downPayment
}); // end function
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en>
<head>
<meta charset=" UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
</head>
<div class="container-fluid" id="containerOne"> <!-- start container one fluid-->
<div class="row" id="modelAndPriceRow"> <!-- first row-->
<div class="form-group">
<label for="listVehicle">Choose:</label>
<select class="form-control" id="listVehicle">
<option value="0"></option>
<option value="vehicleOne">vehicleOne</option>
<option value="vehicleTwo">vehicleTwo</option>
</select>
<input type="text" name="vehicleFinanceValue" id="vehicleFinanceValue" style="display:none">
<input type="text" name="tradeInValue" id="tradeInValue" style="display:none">
<input type="text" name="buyBackValue" id="buyBackValue" style="display:none ">
</div>
<div class="form-group">
<label for="priceVehicle" id="priceVehicleLabel">Cost:</label>
<input type="text " class="form-control " name="priceVehicle" id="priceVehicle" maxlength="8 ">
</div>
</div>
<div class="row " id="financeAndTradeInBoxes"> <!--second row-->
<div class="col-lg-9">
<div class="form-group">
<div class="salesCheckboxes">
<label class="checkbox-inline"> SALES
<input type="checkbox" name="vehicleFinance" id="vehicleFinance"> vehicleFinance
</label>
<label class="checkbox-inline">
<input type="checkbox" name="tradeIn" id="tradeIn"> tradeIn
</label>
</div>
</div>
</div>
</div> <!-- end second row-->
<div class="row">
<div class="priceLabel">Vehicle price in</div>
</div>
<div class="row" id="priceBoxes"> <!-- third row-->
<div class="form-group">
<label for="finalVehiclePricePlusBuyBack">price1 </label>
<input type="text " name="finalVehiclePricePlusBuyBack" id="finalVehiclePricePlusBuyBack" disabled>
</div>
<div class="form-group">
<label for="finalVehiclePrice" id="finalVehiclePriceLabel" >price2 </label>
<input type="text" name="finalVehiclePriceValue" id="finalVehiclePriceValue" disabled>
</div> <!-- end third row-->
</div>
</div>
<div class="container-fluid" id="containerTwo">
<div class="form-group" id="fg1">
<label for="downPayment"> downPayment:</label>
<div class="row">
<input type="text " class="form-control" name="downPayment" id="downPayment" maxlength="8">
<input type="text" class="form-control" name="downPaymentInPercent" id="downPaymentInPercent" disabled>

In your doc read, you have:
var vehicleFinanceValue = parseInt($("input[name=vehicleFinanceValue]").val().replace(/ /g, '')) || 0,
tradeInValue = parseInt($("input[name=tradeInValue]").val().replace(/ /g, '')) || 0,
buyBackValue = parseInt($("input[name=buyBackValue]").val().replace(/ /g, '')) || 0,
finalVehiclePriceValue = parseInt($("input[name=finalVehiclePriceValue]").val().replace(/ /g, '')) || 0,
then in $("input[name=priceVehicle]").change(function() { you have the confusingly formatted:
var vehiclePrice = parseInt($("input[name=priceVehicle]").val().replace(/ /g, '')) || 0,
finalVehiclePriceValue = vehiclePrice;
finalVehiclePricePlusBuyBack = vehiclePrice;
which is essentially:
var vehiclePrice = ...
var finalVehiclePriceValue = vehiclePrice;
finalVehiclePricePlusBuyBack = vehiclePrice;
so you're creating a second variable in this click handler and setting it to the correct value, not the outer defined variable which remains at zero.
A decent IDE would pick this up for you, or passing through jslint, or even using strict mode.
My recommendation is to only declare one variable per var, ie:
var vehicleFinanceValue = parseInt($("input[name=vehicleFinanceValue]").val().replace(/ /g, '')) || 0;
var tradeInValue = parseInt($("input[name=tradeInValue]").val().replace(/ /g, '')) || 0;
var buyBackValue = parseInt($("input[name=buyBackValue]").val().replace(/ /g, '')) || 0;
var finalVehiclePriceValue = parseInt($("input[name=finalVehiclePriceValue]").val().replace(/ /g, '')) || 0;
then, when you make this mistake, it would be (more) obvious:
var vehiclePrice = parseInt($("input[name=priceVehicle]").val().replace(/ /g, '')) || 0;
var finalVehiclePriceValue = vehiclePrice; // <-- clearly shouldn't be `var ..`
finalVehiclePricePlusBuyBack = vehiclePrice;

Related

my js validation doesn't work as I would like (regex)

Hi everyone i have question about my code the plan was that the script was supposed to display message if someone did not enter anything in input or enter somethink thats did not match to my pattern (but if someone lift message will disappear [this doesnt work]) and i dont know where is problem and how to fix it
here is my code:
html
<html lang="pl">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<form action="odp.php" method="post" id="form">
<div>
<label for="imie">Imie</label>
<input type="text" name="imie" id="imie" placeholder="Imie" required>
<span></span>
</div>
<div>
<label for="nazwisko">Nazwisko</label>
<input type="text" name="nazwisko" id="nazwisko" placeholder="Nazwisko" required>
<span></span>
</div>
<div>
<label for="pesel">Pesel</label>
<input type="number" placeholder="pesel" name="pesel" id="pesel" required>
<span></span>
</div><br>
adres zamieszkania:
<div>
<label for="kod">kod</label>
<input type="text" name="kod" id="kod" placeholder="kod" required>
<span></span>
</div>
<div>
<label for="miejscowosc">miejscowość</label>
<input type="text" name="miejscowosc" id="miejscowosc" placeholder="Miejscowość" required>
<span></span>
</div>
<div>
<label for="ulica">ulica</label>
<input type="text" name="ulica" id="ulica" placeholder="Ulica" required>
<span></span>
</div>
<div>
<label for="nrdomu">nr domu</label>
<input type="text" name="nrdomu" id="nrdomu" placeholder="nr domu" required>
<span></span>
</div>
<div>
<label for="nrmieszkania">nr mieszkania</label>
<input type="text" name="nrmieszkania" id="nrmieszkania" placeholder="nr mieszkania">
<span></span>
</div><br>
<div>
<label for="emial">Emial</label>
<input type="email" name="email" placeholder="email" id="email" required>
<span></span>
</div>
<div>
<label for="number">Numer Telefonu</label>
<input type="number" name="nrtel" placeholder="Numer-telefonu" id="number" required>
<span></span>
</div>
<input type="submit" id="submit">
</form>
<script src="main.js"></script>
</body>
</html>
and my js
let nazwisko = document.getElementById('nazwisko');
let pesel = document.getElementById('pesel');
let kod = document.getElementById('kod');
let miejscowosc = document.getElementById('miejscowosc');
let ulica = document.getElementById('ulica');
let nrdomu = document.getElementById('nrdomu');
let nrmieszkania = document.getElementById('nrmieszkania');
let email = document.getElementById('email');
let number = document.getElementById('number');
let span = document.getElementsByTagName('span');
let form = document.getElementById('form');
var arr = [imie,nazwisko,pesel,kod,miejscowosc,ulica,nrdomu,nrmieszkania,email,number];
for(let i = 0; i < arr.length; ++i){
var regex;
console.log(arr[i]);
if(i == 0 || i == 1 || i == 4 || i == 5){
regex = /^[A-Za-zĄĘĆŁŃÓŚŻŹąęćłńóśżź]{3,100}$|^[A-Za-zĄĘĆŁŃÓŚŻŹąęćłńóśżź]+[A-Za-zĄĘĆŁŃÓŚŻŹąęćłńóśżź0-9\s\-]+[A-Za-zĄĘĆŁŃÓŚŻŹąęćłńóśżź0-9]{1,100}$/;
console.log(arr[i].value.match(regex));
}
if(i == 2){
regex = /^[0-9]{11}$/;
console.log(regex);
}
if(i == 3){
regex = /^[0-9]{2}-[0-9]{3}$/i;
console.log(regex);
}
if(i == 6){
regex = /[1-9]|[1-9][0-9]|[1-9][0-9][0-9]|1000/i;
console.log(regex);
}
if(i == 7){
regex = /[0-9]/gm;
console.log(regex);
}
if(i == 8){
regex = /\b[\w\.-]+#[\w\.-]+\.\w{2,4}\b/gi;
console.log(regex);
}
if(i == 9){
regex = /^(?:\+\d\d)?\d{3}(-?)\d{3}\1\d(\d\d)?$/gm;
console.log(regex);
}
arr[i].onblur = function(){
if(arr[i].value.match(regex)){
span[i].innerHTML = "";
}else{
span[i].innerHTML = "Uzupełnij " + arr[i].name;
span[i].style.color = 'red';
}
}
if(i == 7){
arr[i].onblur = span[i].innerHTML = "";
}
}```
the <span></span> tags you are using in the Html do not have an id to which your logic can set the value that you define in the JS
else{
span[i].innerHTML = "Uzupełnij " + arr[i].name;
span[i].style.color = 'red';
}

Auto hide response message

Am JavaScript newbie, and i wanted some help.
the above script can validate valid and invalidate credit card / debit
my problem is that, how can i clear the "invalid credit / debit card number" error message when user has started typing again the card
its like i want to auto clear error message when user has re-type again
<!DOCTYPE html>
<html>
<head>
<style>
</style>
</head>
<body>
<h2>Payment
<img style="visibility: hidden" class="mastercard" src="https://img.icons8.com/color/48/000000/mastercard.png">
<img style="visibility: hidden" class="visacard" src="https://img.icons8.com/color/48/000000/visa.png">
<img style="visibility: hidden" class="discovercard" src="https://img.icons8.com/color/48/000000/discover.png">
<img style="visibility: hidden" class="amexcard" src="https://img.icons8.com/color/48/000000/amex.png">
</h2>
<div class="form-group">
<label for="name-on-card">Name on Card</label>
<input class="cc_name" type="text" name="card-name" class="form-control" placeholder="">
</div>
<div class="form-group">
<label for="cc-number">Credit card number</label>
<input type="text" class="form-control" id="cc_number" name="cc_number" placeholder="" maxlength="20">
<span id="loginError"></span>
</div>
<!--<div class="">
<select class="month_year_select" name="month" id="month">
<option value="">exp month</option>
</select>
</div>
<div class="">
<select class="month_year_select" id="year" name="year">
<option value="">exp year</option>
</select>
</div>-->
<div class="CVV">
<label for="cc-cvv">CVV</label>
<input type="text" class="form-control" id="cc-cvv" name="cc-cvv" placeholder="" maxlength="4">
</div>
<script type="text/javascript">
document.getElementById('cc-cvv').addEventListener('change', CWcheck); //recommended way
document.getElementById('cc_number').onchange = creditCheck; //it is OK too
function CWcheck() { //function name should conventionally start with lower case but isn't big deal
//"this" is the element which fired the event
if (!/^\d{3,4}$/.test(this.value)) {
this.value = '';
this.focus();
alert('CVV is 3 or 4 digits');
}
}
function creditCheck() {
// hide cc logos
var ccImgs = document.querySelectorAll('h2 img');
for (var i = 0, ccImg; ccImg = ccImgs[i]; ++i) {
ccImg.style.visibility = 'hidden';
}
var ccNum = this.value.replace(/\D/g, ''); //remove all non-digits
if (ccNum.length < 15 /*15 is amex*/ || ccNum.length > 16) {
document.getElementById("loginError").innerHTML = "invalid credit / debit card number";
this.focus();
return false;
}
//implement Luhn algorithm
var check = ccNum.split('') //get array
.reverse()
.map(function(el, index) {
return el * (index % 2 + 1); //multiply even positions by 2
})
.join('') //combine array of strings
.split('')
.reduce(function(a, b) { //sum digits
return a + (b - 0);
}, 0);
if (!check || (check % 10)) { //checksum should be none-zero and dividable by 10
document.getElementById("loginError").innerHTML = "invalid credit / debit card number";
this.focus();
return false;
}
//test passed. show card logo
if (/^5[1-5]/.test(ccNum))
document.querySelector('h2 img.mastercard').style.visibility = 'visible';
else if (/^4/.test(ccNum))
document.querySelector('h2 img.visacard').style.visibility = 'visible';
else if (ccNum.length == 15 && /^3[47]/.test(ccNum))
document.querySelector('h2 img.amexcard').style.visibility = 'visible';
else if (/^6011/.test(ccNum))
document.querySelector('h2 img.discovercasd').style.visibility = 'visible';
//and so on
else {
document.getElementById("loginError").innerHTML = "invalid credit / debit card number";
this.focus();
return false;
}
//test passed. format the string
this.value = ccNum
.replace(/^(\d{4})(\d{4})(\d{4})(\d+)$/, '$1 $2 $3 $4');
}
</script>
</body>
</html>
I have added a input event listener to the input, and based on the length of text present in input, I clear the error message (if its length is greater than 0, which marks user has started typing again.)
<!DOCTYPE html>
<html>
<head>
<style>
</style>
</head>
<body>
<h2>Payment
<img style="visibility: hidden" class="mastercard" src="https://img.icons8.com/color/48/000000/mastercard.png">
<img style="visibility: hidden" class="visacard" src="https://img.icons8.com/color/48/000000/visa.png">
<img style="visibility: hidden" class="discovercard" src="https://img.icons8.com/color/48/000000/discover.png">
<img style="visibility: hidden" class="amexcard" src="https://img.icons8.com/color/48/000000/amex.png">
</h2>
<div class="form-group">
<label for="name-on-card">Name on Card</label>
<input class="cc_name" type="text" name="card-name" class="form-control" placeholder="">
</div>
<div class="form-group">
<label for="cc-number">Credit card number</label>
<input type="text" class="form-control" id="cc_number" name="cc_number" placeholder="" maxlength="20">
<span id="loginError"></span>
</div>
<!--<div class="">
<select class="month_year_select" name="month" id="month">
<option value="">exp month</option>
</select>
</div>
<div class="">
<select class="month_year_select" id="year" name="year">
<option value="">exp year</option>
</select>
</div>-->
<div class="CVV">
<label for="cc-cvv">CVV</label>
<input type="text" class="form-control" id="cc-cvv" name="cc-cvv" placeholder="" maxlength="4">
</div>
<script type="text/javascript">
document.getElementById('cc-cvv').addEventListener('change', CWcheck); //recommended way
document.getElementById('cc_number').onchange = creditCheck; //it is OK too
function CWcheck() { //function name should conventionally start with lower case but isn't big deal
//"this" is the element which fired the event
if (!/^\d{3,4}$/.test(this.value)) {
this.value = '';
this.focus();
alert('CVV is 3 or 4 digits');
}
}
function creditCheck() {
// hide cc logos
var ccImgs = document.querySelectorAll('h2 img');
for (var i = 0, ccImg; ccImg = ccImgs[i]; ++i) {
ccImg.style.visibility = 'hidden';
}
var ccNum = this.value.replace(/\D/g, ''); //remove all non-digits
if (ccNum.length < 15 /*15 is amex*/ || ccNum.length > 16) {
document.getElementById("loginError").innerHTML = "invalid credit / debit card number";
this.focus();
return false;
}
//implement Luhn algorithm
var check = ccNum.split('') //get array
.reverse()
.map(function(el, index) {
return el * (index % 2 + 1); //multiply even positions by 2
})
.join('') //combine array of strings
.split('')
.reduce(function(a, b) { //sum digits
return a + (b - 0);
}, 0);
if (!check || (check % 10)) { //checksum should be none-zero and dividable by 10
document.getElementById("loginError").innerHTML = "invalid credit / debit card number";
this.focus();
return false;
}
//test passed. show card logo
if (/^5[1-5]/.test(ccNum))
document.querySelector('h2 img.mastercard').style.visibility = 'visible';
else if (/^4/.test(ccNum))
document.querySelector('h2 img.visacard').style.visibility = 'visible';
else if (ccNum.length == 15 && /^3[47]/.test(ccNum))
document.querySelector('h2 img.amexcard').style.visibility = 'visible';
else if (/^6011/.test(ccNum))
document.querySelector('h2 img.discovercasd').style.visibility = 'visible';
//and so on
else {
document.getElementById("loginError").innerHTML = "invalid credit / debit card number";
this.focus();
return false;
}
//test passed. format the string
this.value = ccNum
.replace(/^(\d{4})(\d{4})(\d{4})(\d+)$/, '$1 $2 $3 $4');
}
document.querySelector("#cc_number").addEventListener("input", function() {
if (document.querySelector("#cc_number").value.length > 0) {
document.getElementById("loginError").innerHTML = "";
}
})
</script>
</body>
</html>
Based on your code, I'd suggest adding a line to clear the error message into your event handler:
document.getElementById('cc-cvv').addEventListener('change', function() {
document.getElementById("loginError").innerHTML = "";
CWcheck();
});
This will reset the message to an empty string every time a keystroke is read. It'll also show error messages when the check comes back as invalid.
Hopes this helps.
There are multiple ways of doing this. With your current setup you could use a class to show and hide the error rather than adding the innerHTML. This class could just be removed after each change. Example with your code, attached.
document.getElementById('cc-cvv').addEventListener('change', CWcheck); //recommended way
document.getElementById('cc_number').onchange = creditCheck; //it is OK too
function CWcheck() { //function name should conventionally start with lower case but isn't big deal
//"this" is the element which fired the event
if (!/^\d{3,4}$/.test(this.value)) {
this.value = '';
this.focus();
alert('CVV is 3 or 4 digits');
}
}
function creditCheck() {
document.getElementById("loginError").classList.remove('card-error--active')
// hide cc logos
var ccImgs = document.querySelectorAll('h2 img');
for (var i = 0, ccImg; ccImg = ccImgs[i]; ++i) {
ccImg.style.visibility = 'hidden';
}
var ccNum = this.value.replace(/\D/g, ''); //remove all non-digits
if (ccNum.length < 15 /*15 is amex*/ || ccNum.length > 16) {
document.getElementById("loginError").classList.add('card-error--active')
this.focus();
return false;
}
//implement Luhn algorithm
var check = ccNum.split('') //get array
.reverse()
.map(function(el, index) {
return el * (index % 2 + 1); //multiply even positions by 2
})
.join('') //combine array of strings
.split('')
.reduce(function(a, b) { //sum digits
return a + (b - 0);
}, 0);
if (!check || (check % 10)) { //checksum should be none-zero and dividable by 10
document.getElementById("loginError").classList.add('card-error--active')
this.focus();
return false;
}
//test passed. show card logo
if (/^5[1-5]/.test(ccNum))
document.querySelector('h2 img.mastercard').style.visibility = 'visible';
else if (/^4/.test(ccNum))
document.querySelector('h2 img.visacard').style.visibility = 'visible';
else if (ccNum.length == 15 && /^3[47]/.test(ccNum))
document.querySelector('h2 img.amexcard').style.visibility = 'visible';
else if (/^6011/.test(ccNum))
document.querySelector('h2 img.discovercasd').style.visibility = 'visible';
//and so on
else {
document.getElementById("loginError").innerHTML = "invalid credit / debit card number";
this.focus();
return false;
}
//test passed. format the string
this.value = ccNum
.replace(/^(\d{4})(\d{4})(\d{4})(\d+)$/, '$1 $2 $3 $4');
}
.card-error{
display:none;
}
.card-error--active{
display:block;
}
<!DOCTYPE html>
<html>
<head>
<style>
</style>
</head>
<body>
<h2>Payment
<img style="visibility: hidden" class="mastercard" src="https://img.icons8.com/color/48/000000/mastercard.png">
<img style="visibility: hidden" class="visacard" src="https://img.icons8.com/color/48/000000/visa.png">
<img style="visibility: hidden" class="discovercard" src="https://img.icons8.com/color/48/000000/discover.png">
<img style="visibility: hidden" class="amexcard" src="https://img.icons8.com/color/48/000000/amex.png">
</h2>
<div class="form-group">
<label for="name-on-card">Name on Card</label>
<input class="cc_name" type="text" name="card-name" class="form-control" placeholder="">
</div>
<div class="form-group">
<label for="cc-number">Credit card number</label>
<input type="text" class="form-control" id="cc_number" name="cc_number" placeholder="" maxlength="20">
<span id="loginError" class="card-error">invalid credit / debit card number</span>
</div>
<!--<div class="">
<select class="month_year_select" name="month" id="month">
<option value="">exp month</option>
</select>
</div>
<div class="">
<select class="month_year_select" id="year" name="year">
<option value="">exp year</option>
</select>
</div>-->
<div class="CVV">
<label for="cc-cvv">CVV</label>
<input type="text" class="form-control" id="cc-cvv" name="cc-cvv" placeholder="" maxlength="4">
</div>
</body>
</html>

Javascript Setting Cookie to Remember form Submission

I've managed to create a form and set a cookie to remember that the user has submitted the form, but the code looks very complicated. Is there not a simpler way to do this? What can I remove? I am NOT SAVING any input data. I just need to ensure that a user fills out the form and is then redirected to the index page. Then when they try to open the page again, they don't have to fill out the form.
<html>
<head>
<title>Document Title</title>
<script type="text/javascript">
cookie_name="landasp"
expdays=365
function set_cookie(name, value, expires, path, domain, secure){
if (!expires){expires = new Date()}
document.cookie = name + "=" + escape(value) +
((expires == null) ? "" : "; expires=" + expires.toGMTString()) +
((path == null) ? "" : "; path=" + path) +
((domain == null) ? "" : "; domain=" + domain) +
((secure == null) ? "" : "; secure");
}
function get_cookie(name) {
var arg = name + "=";
var alen = arg.length;
var clen = document.cookie.length;
var i = 0;
while (i < clen) {
var j = i + alen;
if (document.cookie.substring(i, j) == arg){
return get_cookie_val(j);
}
i = document.cookie.indexOf(" ", i) + 1;
if (i == 0) break;
}
return null;
}
function get_cookie_val(offset){
var endstr = document.cookie.indexOf (";", offset);
if (endstr == -1)
endstr = document.cookie.length;
return unescape(document.cookie.substring(offset, endstr));
}
function saving_cookie(){
var expdate = new Date ();
expdate.setTime (expdate.getTime() + (expdays*24*60*60*1000));
Data="cooked"
set_cookie(cookie_name,Data,expdate)
}
function get_cookie_data(){
inf=get_cookie(cookie_name)
if(!inf){
document.getElementById("display1").style.display="block"
}
else{
document.getElementById("display2").style.display="block"
}
}
</script>
</head>
<body onload="get_cookie_data()">
<div id="display1" style="display:none">
<div class="register">
<form action="index.html" onsubmit="saving_cookie()">
<div>Name<br>
<input name="name" type="text" id="name" class="inputf">
<br>Tel<br>
<input name="tel" type="text" id="tel" class="inputf">
<br><br>
<input type="submit" name="Submit" value="Submit" class="button1">
</div>
</form>
</div>
<div id="display2" style="display:none">
<div class="register">
<p><strong>REGISTERED</strong></p>
</div>
</div>
</body>
</html>
Yes, the cookie scripts are normally that big. You can externalise them in a jsfile
However if you do not need the cookie on the server, we nowadays use sessionStorage or localStorage
Also reversing the test
NOTE this script completely replaces yours
const cookie_name = "landasp";
window.addEventListener("load", function() {
const inf = localStorage.getItem(cookie_name);
if (inf) {
document.getElementById("display2").style.display = "block"
setTimeout(function() {location.replace("index.html"},2000)
} else {
document.getElementById("display1").style.display = "block"
}
document.getElementById("regForm").addEventListener("submit", function() {
localStorage.setItem(cookie_name, "done");
})
})
adding an ID to the form and removing inline event handlers
<div id="display1" style="display:none">
<div class="register">
<form action="index.html" id="regForm">
<div>Name<br>
<input name="name" type="text" id="name" class="inputf">
<br>Tel<br>
<input name="tel" type="text" id="tel" class="inputf">
<br><br>
<input type="submit" name="Submit" value="Submit" class="button1">
</div>
</form>
</div>
<div id="display2" style="display:none">
<div class="register">
<p><strong>REGISTERED</strong></p>
</div>
</div>
</div>

NaN or 0 shows up in sum up

In the process of summing up input values, overall is always showed up NaN or O ( sum up function below). I can't sum values up. All values are Number and their variable also Number according to the console information. Everywhere I use parseInt and Number methods.
The sum up function is also used with parseInt method. I had to add the logical operator || in the sum up function, after that, it always showed up 0.
// points declaration for rate determenation
$(function () {
$("#name_vehicle").change(function () {
var vehicle_value = $(this).val(),
vehicle_point = $("#vehicle_point").val();
vehicle_point = ( vehicle_value == "1" ) ? 1 :
( vehicle_value == "2" ) ? 1 :
( vehicle_value == "3" ) ? 1 :
( vehicle_value == "4" ) ? 1 :
( vehicle_value == "5" ) ? 1:
(vehicle_value == "6" ) ? 2 : 0;
$("#vehicle_point").val( vehicle_point );
console.log ( vehicle_point );
});// end change
}); // end ready
$(function () {
$("#term").change(function () {
var tv = $(this).val();
var tp = $("#term_point").val();
tp = ( tv == "1") ? 24:
( tv == "2") ? 36 :
( tv == "3") ? 48:
( tv == "4") ? 60 : 0;
$("#term_point").val( tp );
console.log ( tp );
}); // end change
}); // end ready
$(function () {
$("input").change(function () {
var cp = parseInt($("input[name=carPrice").val());
var d = parseInt($("input[name=deposit").val());
var ae = parseInt($("input[name=add_equip").val());
var c = parseInt ($("input[name=casco]").val());
var tp = parseInt($("input[name=term_point").val());
var result = ( ( cp + ae ) - d + c );
var pd = ((d / ( cp + ae )) * 100); // DEPOSIT IN %
$("#overall").val( result );
console.log ( result );
$("#p_deposit").val( pd );
console.log ( pd );
console.log ( typeof pd );
var cl_points = parseInt($("input[name=cl_points").val());
var bl_points = parseInt($("input[name=bl_points").val());
if ( pd >= 20 && pd < 39.99 ) {
cl_points = 1;
bl_points = 1;
}
else if ( pd > 39.99 && pd < 49.99) {
cl_points = 1;
bl_points = 5;
}
else if ( pd > 49.99 && pd <= 55 ) {
cl_points = 1;
bl_points = 5;
}
else if ( pd > 55 && pd < 99.99 ) {
cl_points = 1;
bl_points = 0;
}
$("#cl_points").val( cl_points );
$("#bl_points").val( bl_points );
console.log ( cl_points );
console.log ( bl_points );
}); // end change
}); // end ready
$(function () {
var sum = 0;
$(".points").each(function () {
sum += parseInt($(this).val()) || 0;
$("#overallPoints").val( sum ) ;
console.log (sum);
console.log ( typeof sum);
}); // end each
}); // end ready
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.3.1.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<!-- first header-->
<div class="image-container">
<div class="text"></div>
</div>
<br>
<div class="container-fluid">
<div class="row">
<div class="col-lg-4">
<!-- box one-->
<i class="fa fa-car" id="v1" style="font-size:84px;color:white"><span class="w1">А</span></i>
<form>
<div class="form-group">
<label class="l1" for="name_vehicle">В</label>
<select multiple class="form-control" id="name_vehicle">
<option value="1">A</option>
<option value="2">T</option>
<option value="3">Q</option>
<option value="4">X</option>
<option value="5">M</option>
<option value="6">J</option>
</select>
<input type="text" class="points" id="vehicle_point" style="display:none">
<!-- POINT ONE-->
</div>
</form>
<form>
<div class="form-group">
<label class="l1" for="carPrice">С:</label>
<input type="text" class="form-control" id="carPrice" name="carPrice" value="0">
</div>
<div class="form-group">
<label class="l1" for="add_equip">о:</label>
<input type="text" class="form-control" id="add_equip" name="add_equip" value="0">
</div>
</form>
</div>
<div class="col-lg-4">
<!-- box two-->
<i class="fa fa-money" style="font-size:84px;color:white"><span class="w1">К</span></i>
<form>
<div class="form-group">
<label class="l1" for="deposit">П</label>
<input type="text" class="form-control" id="deposit" name="deposit" value="0">
<input type="text" id="car_loan" style="display:none" name="car_loan">
<!-- CAR LOAN SUM-->
</div>
<div class="form-group">
<label class="l1" for="term">С</label>
<select multiple class="form-control" id="term">
<option value="1">24 </option>
<option value="2">36 </option>
<option value="3">48 </option>
<option value="4">60 </option>
</select>
<input type="text" class="points" id="term_point" style="display:none" name="term_point">
<!-- POINT TWO-->
</div>
<div class="form-group">
<label class="l1" for="casco">К:</label>
<input type="text" class="form-control" id="casco" name="casco" value="0">
<input type="text" id="overall" style="display:none" name="overall">
<!--SUM UP-->
<input type="text" id="p_deposit" style="display:none">
<!-- DEPOSIT IN %-->
<input type="text" class="points" id="p_deposit_point" style="display:none" name="p_deposit_point">
<!-- POINT THREE-->
</div>
</div>
</div>
First when you have a number, you do not have to use Number() to ensure it is a number.
The logic here is wrong:
(tv == "1") ? tp = Number(24): Number(0);
(tv == "2") ? tp = Number(36): Number(0);
(tv == "3") ? tp = Number(48): Number(0);
(tv == "4") ? tp = Number(60): Number(0);
You can not use a ternary operator here for this. When you say tv=2, first one will set it to zero, second would set it to 36, third will set it back to 0.
A ternary operator would have to look like:
(tv == "1") ? tp = Number(24):
(tv == "2") ? tp = Number(36):
(tv == "3") ? tp = Number(48):
(tv == "4") ? tp = Number(60): Number(0);
But that really makes little sense to do.
You would be better off to use a switch statement of if/else if
switch (tv) {
case "1": tp = 24; break;
case "2": tp = 36; break;
case "3": tp = 48; break;
case "4": tp = 60; break;
case default: tp = 0; break;
}
Same thing applies with vehicle point.

Random jQuery for Cordova App

I have a problem with my jQuery Code
I want to randomize numbers in a range and I wrote this:
jQuery Code:
$("#button").click(function() {
var numLow = $("#lownumber").value();
var numHigh = $("#highnumber").value();
var adjustedHigh = (parseFloat(numHigh) - parseFloat(numLow)) + 1;
var numRand = Math.floor(Math.random() * adjustedHigh) + parseFloat(numLow);
if ((isFinite(numLow)) && (isFinite(numHigh)) && parseFloat(numLow) <= parseFloat(numHigh) && (numLow != '') && (numHigh != '')) {
$("#random").text(numRand);
} else {
$("#random").text("Ops... an error!");
}
return false;
});
HTML page:
<body>
<div class="text">Random</div>
<input type="text" id="lownumber" value="1">
<input type="text" id="highnumber" value="100">
<input type="submit" id="button" value="Generate!">
<div id="random"></div>
<script type="text/javascript" src="js/random.js"></script>
<script type="text/javascript" src="cordova.js"></script>
<script type="text/javascript" src="js/index.js"></script>
</body>
PLEASE HELP ME! T.T
It is suppose to be .val() Not .value() So now it works..
$("#button").click(function(){
var numLow = $("#lownumber").val();
var numHigh = $("#highnumber").val();
var adjustedHigh = (parseFloat(numHigh) - parseFloat(numLow))+1;
var numRand = Math.floor(Math.random()*adjustedHigh)+parseFloat(numLow);
if((isFinite(numLow)) && (isFinite(numHigh)) && parseFloat(numLow) <= parseFloat(numHigh) && (numLow != '') && (numHigh != '')){
$("#random").text(numRand);
} else {
$("#random").text("Ops... an error!");
}
return false;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<div class="text">Random</div>
<input type="text" id="lownumber" value="1">
<input type="text" id="highnumber" value="100">
<input type="submit" id="button" value="Generate!">
<div id="random"></div>
</body>

Categories