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.
Related
in my JavaScript
$("#inputDatabaseName").on("keyup", function(e) {
alert("Changed!");
console.info(this.value);
var nilaicli = this.value,
skorcli = document.getElementById("skorclis");
var cli1 = parseFloat(nilaicli.value) || 2;
var x = cli1.toFixed(2);
if (x <= 39.99 && x >= 0) {
skorcli.value = 1; //its the only come out and dont want change again if i input another number in inputid="inputDatabaseName". :(
} else if (x >= 40.0 && x <= 59.99) {
skorcli.value = 2;
} else if (x >= 60.0 && x <= 79.99) {
skorcli.value = 3;
} else if (x >= 80.0 && x <= 89.99) {
skorcli.value = 4;
} else if (x >= 90.0 && x <= 100) {
skorcli.value = 5;
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col-lg-3">
<div class="card card-chart">
<div class="card-header">
<div class="row">
<p> Input CLI</p>
</div>
<div class="card-body">
<div class="row">
<div class="col-8">
<label>Nilai CLI : </label>
<input type="text" name="nama" class="col-sm-4 nilaicli" id="inputDatabaseName">
<br>
</div>
</div>
<div class="row">
<div class="col-8">
<label> Skor CLI : </label>
<input type="text" name="nama" class="col-sm-3" id="skorclis" readonly="true" onkeypress="return onlyNumberKey(event)">
</div>
</div>
</div>
</div>
</div>
</div>
i want change value in inputid="skorclis" again if i input something in inputid="inputDatabaseName".
but my script dont want change value at inputid="skorclis" repeatly. only want the first if statement. and dont want change again. how to make it become change again?
$("#inputDatabaseName").on("keyup", function(e) {
const nilaicli = this.value;
const cli1 = parseFloat(nilaicli) || 2;
const x = cli1.toFixed(2);
hanldeChange(x);
});
const hanldeChange = (x) => {
const skorcli = document.getElementById("skorclis");
console.info(x);
if (x <= 39.99) {
skorcli.value = 1;
} else if (x <= 59.99) {
skorcli.value = 2;
} else if (x <= 79.99) {
skorcli.value = 3;
} else if (x <= 89.99) {
skorcli.value = 4;
} else if (x <= 100) {
skorcli.value = 5;
}
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col-lg-3">
<div class="card card-chart">
<div class="card-header">
<div class="row">
<p> Input CLI</p>
</div>
<div class="card-body">
<div class="row">
<div class="col-8">
<label>Nilai CLI : </label>
<input type="text" name="nama" class="col-sm-4 nilaicli" id="inputDatabaseName">
<br>
</div>
</div>
<div class="row">
<div class="col-8">
<label> Skor CLI : </label>
<input type="text" name="nama" class="col-sm-3" id="skorclis" readonly="true" onkeypress="return onlyNumberKey(event)">
</div>
</div>
</div>
</div>
</div>
</div>
Have look to that:
const myForm = document.querySelector('#my-form') // use a form, it is
// usefull to access on myForm.nilaicli
// element or any one else
myForm.nilaicli.addEventListener('input',function() // use input event, it's also work with mouse copy/paste
{
let x = parseFloat(this.value) || 2
this.value = x // .toFixed(2)
switch (true)
{
case (x >= 0 && x < 40) : myForm.skorclis.value = 1; break;
case (x >= 40 && x < 60) : myForm.skorclis.value = 2; break;
case (x >= 60 && x < 80) : myForm.skorclis.value = 3; break;
case (x >= 80 && x < 90) : myForm.skorclis.value = 4; break;
case (x >= 90 && x <= 100) : myForm.skorclis.value = 5; break;
}
})
myForm.onsubmit = e => e.preventDefault() // disable form submit
fieldset {
display : block;
margin : 1em;
width : 17em;
}
label {
display : block;
margin : 1em;
}
label input {
float : right;
padding : 0 .7em;
width : 9em;
}
<form id="my-form">
<fieldset>
<legend>Input CLI</legend>
<label>
Nilai CLI :
<input type="text" name="nilaicli">
</label>
<label>
Skor CLI :
<input type="text" name="skorclis" readonly >
</label>
</fieldset>
</form>
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>
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;
So I have something like this...
I have a form where you select your gender and input your weight. each gender has different ranges of prices for example if your a male and your weight is greater than 200 your price is 20, if your a female and your weight is greater than 200 your price is 15, and if your male and your weight is less than 200 your price is 10, for the female if her weight is less than 200 her price is 7 . i have been trying to make it possible with jquery and PHP but it only seems to work with select option and won't work with input data.
this is my index.php
<div class="container">
<div class="row">
<div class="col-xs-3 col-xs-offset-2">
<h3>gender:</h3>
<!-- select gender -->
<select class="form-control" id="gender">
<option>female</option>
<option>male</option>
</select>
</div>
<div class="col-xs-3">
<h3>weight </h3>
<!-- input weight -->
<input type="" name="weight" id="weight">
</div>
</div>
<div id="ticketInfo">
<h3 id="yourTicket">No gender Selected</h3>
</div>
</div>
<script src="js/jquery-1.12.2.js"></script>
<script src="js/bootstrap.js"></script>
<script src="js/scripts.js"></script>
this is my script
function Ticket(gender, weight) {
this.gender=gender;
this.weight=weight;
}
Ticket.prototype.getPrice=function() {
var price;
if((this.gender==="male ")||(this.weight=>"200 ")){
price=20;
}
if((this.gender==="female ")||(this.weight=>"200 ")) {
price=15;
}
if((this.gender==="male ")||(this.weight=<"200 ")) {
price=10;
}
if((this.gender==="female ")||(this.weight=<"200 ")) {
price=7;
}
return price;
}
$("select").change(function() {
var genderOptions=[];
$("select option:selected").each(function() {
genderOptions.push($(this).text() + " ");
});
var newTicket = new
Ticket(genderOptions[0],genderOptions[1],genderOptions[2]);
$("#yourTicket").text(newTicket.gender + newTicket.weight + " $" +
newTicket.getPrice().toFixed(2));
});
at the end in trying to multiply the price by the weight. any help will be really appreciated, thanks in advance.
Try this with Syed's solution.
Logic should be using && operator not ||
function Ticket(gender, weight) {
this.gender=gender;
this.weight=weight;
}
Ticket.prototype.getPrice=function() {
var price;
if(this.gender==="male" && this.weight > 200){
price=20;
}
else if(this.gender==="female" && this.weight > 200) {
price=15;
}
else if(this.gender==="male" && this.weight <= 200) {
price=10;
}
else if(this.gender==="female" && this.weight <= 200) {
price=7;
}
return price;
}
$("#calculate").click(function() {
var genderOptions=[];
$("select option:selected").each(function() {
genderOptions.push($(this).text() + " ");
});
var newTicket = new
Ticket($("#gender").val(),$('#weight').val());
var multiplyVal = newTicket.weight * newTicket.getPrice();
$("#yourTicket").text("Gender: " + newTicket.gender + " Weight: " + newTicket.weight + " $" + newTicket.getPrice().toFixed(2) + " and your multiplied value is " + multiplyVal);
});
<div class="col-xs-3 col-xs-offset-2">
<h3>gender:</h3>
<!-- select gender -->
<select class="form-control" id="gender">
<option value="female" selected>female</option>
<option value="male">male</option>
</select>
</div>
<div class="col-xs-3">
<h3>weight </h3>
<!-- input weight -->
<input type="" name="weight" id="weight">
</div>
<div id="ticketInfo">
<h3 id="yourTicket">No gender Selected</h3>
</div>
<button id="calculate" >Calculate</button>
Your question is unclear.as per my understanding I provide you a solution.
You have mistakes in your if condition. for eg. you need to check as >= instead you checked as => which is wrong.
Also it should be && instead of ||
And you missed to pass the weight variable to the Ticket class.
remove quotes around 200 in your if condition
you have pushed a space in genderOptions. so I removed it.
I fixed these issues.
function Ticket(gender, weight) {
this.gender=gender;
this.weight=weight;
}
Ticket.prototype.getPrice=function() {
var price;
if(this.gender==="male" && this.weight > 200 ){
price=20;
}
else if(this.gender==="female" && this.weight > 200 ) {
price=15;
}
else if(this.gender==="male" && this.weight <= 200 ) {
price=10;
}
else if(this.gender==="female" && this.weight <= 200 ) {
price=7;
}
return price;
}
$("select").change(function() {
var genderOptions=[];
$("select option:selected").each(function() {
genderOptions.push($(this).text());
});
var newTicket = new Ticket(genderOptions[0] , $('#weight').val());
var multiplyVal = newTicket.weight * newTicket.getPrice();
$("#yourTicket").text(newTicket.gender + newTicket.weight + " $" + newTicket.getPrice().toFixed(2) + " and your multiplied value is " + multiplyVal);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="row">
<div class="col-xs-3 col-xs-offset-2">
<h3>gender:</h3>
<!-- select gender -->
<select class="form-control" id="gender">
<option value="female">female</option>
<option value="male">male</option>
</select>
</div>
<div class="col-xs-3">
<h3>weight </h3>
<!-- input weight -->
<input type="" name="weight" id="weight">
</div>
</div>
<div id="ticketInfo">
<h3 id="yourTicket">No gender Selected</h3>
</div>
</div>
Remove the empty string added in gender options.push.Afterwards ,working fine
genderOptions.push($(this).text())
Here is the code:
<form class="ui form attached fluid loading segment" onsubmit="return contact(this)">
<div class="field">
<label>Preferred Tour</label>
<div class="field">
<?php
$conn=mysqli_connect('####','####','####','####');
echo '<select required id="tourInfo">';
echo '<option value="" selected disabled>--Preferred Tour--</option>';
$db = mysqli_query($conn, "SELECT `id`,`tourprice`,`tourname` FROM `available_tours`");
while ($d=mysqli_fetch_assoc($db)) {
echo "<option value=".$d['id']." id=".$d['tourname']. " data-price=".$d['tourprice'].">".$d['tourname']."</option>";
}
echo "</select>";
?>
</div>
</div>
<div class="field" id="hiddenTortu" style="display: none;">
<label>Attention</label>
<div class="ui icon">
<p><b>The minimum of people for this tour is 5, less than 5 the tour is not realisable</b></p>
</div>
</div>
<div class="field">
<label>Available Time</label>
<div class="field">
<?php
$conn=mysqli_connect('####','####','####','####');
echo '<select name="gender" required id="timeInfo">';
echo '<option value="" selected disabled>--Preferred Time--</option>';
$db = mysqli_query($conn, "SELECT `time_real` FROM `available_time`");
while ($d=mysqli_fetch_assoc($db)) {
echo "<option value=".$d['time_real'].">".$d['time_real']."</option>";
}
echo "</select>";
?>
</div>
</div>
<div class="two fields">
<div class="field" id="pax">
<label>Please specify the number of People according to the perred tour selection</label>
Here starts the problem with the following script according to the tour selection I'm trying to set up a minimum and maximum so that the user can't choose more numbers for the people on the tour.
The problem is that when the user select first one option, and then realised that the best option is another one, when he/she does another selection the input created with jQuery that was appended remains and because of the new selection a new input is created.
The intention is that if the user chooses option 1 the input append appears according to option one, but if the user regrets and prefers option 2 that the input for the option 1 disappears and a new input according to option 2 appears and so on for the entire if conditions.
<script>
$(document).ready(function(){
$('#tourInfo').on('change', function() {
if ( this.value == '1')
{
$("#pax").append($('<input placeholder="Number of People" type="number" id="peopleInfo" min="1" max="2" value="1" required>'));
(function ($) {
$.fn.restrict = function () {
return this.each(function(){
if (this.type && 'number' === this.type.toLowerCase()) {
$(this).on('change', function(){
var _self = this,
v = parseFloat(_self.value),
min = parseFloat(_self.min),
max = parseFloat(_self.max);
if (v >= min && v <= max){
_self.value = v;
}
else {
_self.value = v < min ? min : max;
}
});
}
});
};
})(jQuery);
$('#peopleInfo').restrict();
}
else if (this.value == '2')
$("#pax").append($('<input placeholder="Number of People" type="number" id="peopleInfo" min="3" max="5" value="3" required>'));
(function ($) {
$.fn.restrict = function () {
return this.each(function(){
if (this.type && 'number' === this.type.toLowerCase()) {
$(this).on('change', function(){
var _self = this,
v = parseFloat(_self.value),
min = parseFloat(_self.min),
max = parseFloat(_self.max);
if (v >= min && v <= max){
_self.value = v;
}
else {
_self.value = v < min ? min : max;
}
});
}
});
};
})(jQuery);
$('#peopleInfo').restrict();
}
else if (this.value == '3')
{
$("#pax").append($('<input placeholder="Number of People" type="number" id="peopleInfo" min="6" max="15" value="6" required>'));
(function ($) {
$.fn.restrict = function () {
return this.each(function(){
if (this.type && 'number' === this.type.toLowerCase()) {
$(this).on('change', function(){
var _self = this,
v = parseFloat(_self.value),
min = parseFloat(_self.min),
max = parseFloat(_self.max);
if (v >= min && v <= max){
_self.value = v;
}
else {
_self.value = v < min ? min : max;
}
});
}
});
};
})(jQuery);
$('#peopleInfo').restrict();
}...
...});
};
})(jQuery);
$('#peopleInfo').restrict();
}
});
});
</script>
</div>
<div class="field">
<label><br>Date of Tour</label>
<input type="text" readonly required id="tourDate" class="datepicker-here form-control" placeholder="ex. August 03, 1998">
</div>
</div>
<div style="text-align:center">
<div>
<label>Ensure all details have been filled correctly</label>
</div>
<button class="ui green submit button">Submit Details</button>
</div>
</form>
</div>
Move your script out from inside the div with id pax, then
Clear your html of the element with id pax before appending:
//Using JQuery
$('#pax').html('');