put html in input field - javascript

I want that in the input field for a user there is predefined (in the "Einkommen" field) text (see picture).
How can I do this?
Here is my code for the other fields:
<script type="text/javascript">
function sumValues() {
var num1;
var num3;
var num4;
num1 = Number(document.formcalc.txtnum1.value);
num3 = ((num1 * 0.12) - (num1 * 0.118)) / 12;
num4 = ((num1 * 0.12) - (num1 * 0.118)) * 15500;
document.formcalc.txtres.value = 'Fr. ' + Math.round(num3) + '.-';
document.formcalc.txtres2.value = 'Fr. ' + Math.round(num4) + '.-';
// document.getElementById("result").value = res;
}
</script>

It's not really clear what you're asking.
But in HTML with JavaScript, what you have commented:
document.getElementById("result").value = "90000";
is actually correct if your intention is to set a value over the input.
Also, I'm wondering if by "predefined" you mean actual text or just a placeholder?

this is my code:
<div class="container content-center" id="margin">
<form name="formcalc">
<div class="form-group row">
<label for="staticEmail" class="col-sm-2 col-form-label">Einkommen</label>
<div class="col-sm-10">
<!-- <div class="input-group-addon">Fr.</div> -->
<input type="text" class="form-control" name="txtnum1">
</div>
</div>
<fieldset disabled>
<div class="form-group row">
<label for="staticEmail" class="col-sm-2 col-form-label">Dein Ersparniss / Jahr</label>
<div class="col-sm-10">
<input type="text" class="form-control" name="txtres" readonly>
</div>
</div>
<div class="form-group row">
<label for="staticEmail" class="col-sm-2 col-form-label">Verlust Stadt Wil / Jahr</label>
<div class="col-sm-10">
<input type="text" class="form-control" name="txtres2" readonly>
</div>
</div>
</fieldset>
<input type="button" class="btn btn-danger" value="Berechnen" onClick="sumValues()">
</form>
<hr class="featurette-divider">
<section class="container">
<p class="lead" id="lead"> Ist es dir Wert, dass deine Stadt pro Jahr XXX weniger Budget zur Verfügung hat
und du XXX mehr pro Jahr in der Tasche hast?
</p>
</section>
<hr class="featurette-divider">
<small class="d-block mb-3 text-muted">created by Behar Zenuni</small>
</div>
I want for the input field to already have "Fr." inside before a user puts a number in.

If I understand what you want, you want to add the "Fr." prefix and ".-" suffix to your value automatically, right? One way to do this is using the onBlur event, so when the user clicks / navigates out of the field, the code will add the rest.
An example, would be with your HTML being:
<input name="einkommen" type="text" value="" onblur="formatValue(this)">
and add this function to your Javascript:
ES5:
function formatValue(e) {
e.value = 'Fr. ' + e.value + '.-';
};
ES6:
const formatValue = e => e.value = `Fr. ${e.value}.-`;

I think this is what you want:
$(document).ready(function(){
sumValues = function() {
var num1;
var num3;
var num4;
num1 = 90000;
num3 = ((num1 * 0.12) - (num1 * 0.118)) / 12;
num4 = ((num1 * 0.12) - (num1 * 0.118)) * 15500;
$('input[name="txtnum1"]').val(num1);
$('input[name="txtres1"]').val('Fr. ' + Math.round(num3) + '.-');
$('input[name="txtres2"]').val('Fr. ' + Math.round(num4) + '.-');
$('input[name="txtnum1"]').addClass( "colored-background" );
};
})
.colored-background {
background: yellow !important;
}
<link rel="stylesheet" type="text/css" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css">
<div class="container">
<div class="form-group row">
<label for="staticEmail" class="col-sm-2 col-form-label">Einkommen</label>
<div class="col-sm-10">
<input type="text" class="form-control" name="txtnum1" value="Fr. .-" readonly>
</div>
</div>
<div class="form-group row">
<label for="staticEmail" class="col-sm-2 col-form-label">Dein Ersparniss / Jahr</label>
<div class="col-sm-10">
<input type="text" class="form-control" name="txtres1" value="Fr. .-" readonly>
</div>
</div>
<div class="form-group row">
<label for="staticEmail" class="col-sm-2 col-form-label">Dein Ersparniss / Jahr</label>
<div class="col-sm-10">
<input type="text" class="form-control" name="txtres2" value="Fr. .-" readonly>
</div>
</div>
<input type="button" class="btn btn-danger" value="Berechnen" onClick="sumValues()">
</div>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js"></script>
<script type="text/javascript" src="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js"></script>

Related

Show Thousands Separator within input field only

I have added a thousand separator by Javascript keyup to an input field within a standard form:
Form
<form>
<div class="row mt20">
<div class="col-md-3 col-sm-12 col-xs-12">
</div>
<div>
<input id="cal2_txtLoan" class="wpcf7-form-control wpcf7-text form-control investment-class-form" type="text" placeholder="วงเงินกู้(บาท)">
</div>
</div>
<div class="row mt20">
<div class="col-md-6 col-sm-9 col-xs-9">
<input id="cal2_txtTenor" class="wpcf7-form-control wpcf7-text form-control investment-class-form" type="number" placeholder="ระยะเวลากู้ 1-30 ปี">
</div>
</div>
<div class="row mt20">
<div class="col-md-6 col-sm-9 col-xs-9">
<input id="cal2_txtInterestRate" class="wpcf7-form-control wpcf7-text form-control investment-class-form" type="number" placeholder="ดอกเบี้ย(%)">
</div>
</div>
<div class="row mt20">
<div class="col-md-offset-3 col-md-6 col-sm-offset-0 col-sm-9 col-xs-offset-0 col-xs-9">
<div class="row">
<div class="col-xs-6">
<button type="button" id="cal2_btnCalculate" class="button investment-button">คำนวณ</button>
</div>
</div>
</div>
</div>
<div class="row mt20">
<div class="col-md-3 col-sm-12 col-xs-12">
<label class="investment-list">สรุปยอดผ่อนต่อเดือน (บาท)</label> <input id="cal2_txtInstallment" class="wpcf7-form-control wpcf7-text form-control investment-class-form" disabled="disabled" type="text"> <span class="investment-list" style="color:red;">* ผลลัพธ์จากการคำนวณ เป็นเพียงผลการคำนวณเบื้องต้นเท่านั้น โปรดติดต่อธนาคารเพื่อคำนวณยอดที่ถูกต้องอีกครั้งหนึ่ง</span>
</div>
</div>
</form>
Javascript Event Keyup
<script>
var cal2_txtLoan = document.getElementById('cal2_txtLoan');
cal2_txtLoan.addEventListener('keyup', function() {
var val = this.value;
val = val.replace(/[^0-9\.]/g,'');
if(val != "") {
valArr = val.split('.');
valArr[0] = (parseInt(valArr[0],10)).toLocaleString();
val = valArr.join('.');
}
this.value = val;
});
</script>
It works correctly, but now my form cannot submit because of the comma "," in the value
How can I display my decimal separator in the input field, but only submit the value.
Rest of my calculation for reference:
<script>
function CalculatePMT(pv, rate, years) {
return Math.round(pv * (rate / 100 / 12) / (1 - 1 / Math.pow ((1 + rate / 100 / 12) , ( years * 12))));
}
/************** CALCULATE LOAN *************/
$("#cal2_btnCalculate").click(Calculate2);
function Calculate2(event) {
var years = $("#cal2_txtTenor").val();
var rate = $("#cal2_txtInterestRate").val();
var pv = $("#cal2_txtLoan").val();
if (CheckForDigit(years) && CheckForDigit(rate) && CheckForDigit(pv)) {
var ir = (rate / 100) * 100; // For LH, add 1 more
var installment = CalculatePMT(pv, ir, years);
$("#cal2_txtInstallment").val(FormatNumberToString(installment));
$("#cal2_txtMinimumIncome").val(FormatNumberToString(installment ));
} else
alert("ไม่สามารถคำนวนวงเงินสินเชื่อเพื่อการซื้อบ้านได้");
}
/*****************************************/
});
</script
<form onsubmit="return deleteThousandSeparator(event)">
...
</form>
function deleteThousandSeparator(){
const cal2_txtLoan = document.getElementById('cal2_txtLoan');
cal2_txtLoan.value = cal2_txtLoan.value.replace('.','')
}

Checking box values and disable button and show error message in Javascript

I need to make sure the value of a particular set of boxes should not exceed the value of other sets of boxes...
Set 1: Consultation fee, Other fee (total_fee will show the sum of these)
Set 2: cash, gpay, upi, card, others (total fee paid will show the sum of these)
The above action working pretty well...
Now, I want to make sure set 2 of total value should not exceed set 1 of total value. if so, I need to disable btn and also need to show an error message as "Sum of Receiving Payment exceeds Total Fee, Please Check!"...
How to do that?!
<html>
<head>
<!-- CSS only -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.2.0/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-gH2yIJqKdNHPEq0n4Mqa/HGKIhSkIHeL5AyhkYV8i59U5AR6csBvApHHNl/vI1Bx" crossorigin="anonymous">
<!-- JavaScript Bundle with Popper -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.2.0/dist/js/bootstrap.bundle.min.js" integrity="sha384-A3rJD856KowSb7dwlZdYEkO39Gagi7vIsF0jrRAoQmDKKtQBHUuLZ9AsSv4jD4Xa" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js" integrity="sha512-894YE6QWD5I59HgZOGReFYm4dnWc1Qt5NtvYSaNcOP+u1T9qYdvdihz0PPSiiqn/+/3e7Jo4EaG7TubfWGUrMQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<style>
.error-text {
font-size: 14px;
color: red;
margin-top: 15px;
}
</style>
<!-- Total Receiving Fee Calculation from Cash, Gpay, UPI, Card, Others -->
<script type="text/javascript">
$(function() {
const paid_cash = document.getElementById("paid_cash");
const paid_gpay = document.getElementById("paid_gpay");
const paid_upi = document.getElementById("paid_upi");
const paid_card = document.getElementById("paid_card");
const paid_others = document.getElementById("paid_others");
const total_fee_paid = document.getElementById("total_fee_paid");
document.getElementById("paid_cash").addEventListener("input", sum);
document.getElementById("paid_gpay").addEventListener("input", sum);
document.getElementById("paid_upi").addEventListener("input", sum);
document.getElementById("paid_card").addEventListener("input", sum);
document.getElementById("paid_others").addEventListener("input", sum);
function sum() {
total_fee_paid.value = Number(paid_cash.value) + Number(paid_gpay.value) + Number(paid_upi.value) + Number(paid_card.value) + Number(paid_others.value);
}
});
</script>
<!-- Total Fee Calculation from Consultation fee and Other fee-->
<script type="text/javascript">
$(function() {
const fee1 = document.getElementById("visit_cons_fee");
const fee2 = document.getElementById("visit_other_fee");
const total_fee = document.getElementById("total_fee");
document.getElementById("visit_cons_fee").addEventListener("input", sum);
document.getElementById("visit_other_fee").addEventListener("input", sum);
function sum() {
total_fee.value = Number(fee1.value) + Number(fee2.value);
}
});
</script>
<script type="text/javascript">
// access the button from the html
const btn = document.getElementById("btnSubmit");
// access input boxes total_fee, total_fee_paid
const [visit_cons_fee, visit_other_fee, paid_cash, paid_gpay, paid_upi, paid_card, paid_others] = [
document.getElementById("visit_cons_fee"),
document.getElementById("visit_other_fee"),
document.getElementById("paid_cash"),
document.getElementById("paid_gpay"),
document.getElementById("paid_upi"),
document.getElementById("paid_card"),
document.getElementById("paid_others")
];
// a generic method to validate if prices indicate
// that 'submit' button should be disabled
// as well as render an error notification
const validatePrices = () => {
btn.disabled = (+visit_cons_fee.value + +visit_other_fee.value < +paid_cash.value + +paid_gpay.value + +paid_upi.value + +paid_card.value + +paid_others.value);
document.getElementById("error").innerText = (+visit_cons_fee.value + +visit_other_fee.value < +paid_cash.value + +paid_gpay.value + +paid_upi.value + +paid_card.value + +paid_others.value ?
'Sum of Receiving Payment exceeds Total Fee, Please Check!' :
''
);
};
// add event-listener to each input to invoke the validate method
[paid_cash, paid_gpay, paid_upi, paid_card, paid_others].forEach(
box => {
box.addEventListener('keyup', validatePrices)
});
</script>
</head>
<body>
<div class="row">
<div class="col-xl-4">
<div class="form-group">
<label class="gr"><b>Consulation Fees:</b><span class="text-danger">*</span></label><input type="number" class="form-control" id="visit_cons_fee" name="visit_cons_fee" required min="0">
</div>
</div>
<div class="col-xl-4">
<div class="form-group">
<label class="gr"><b>Other Charges:</b></label><input type="number" class="form-control" id="visit_other_fee" name="visit_other_fee" min="0">
</div>
</div>
<div class="col-xl-4">
<div class="form-group">
<label class="gr"><b>Total Fee:</b></label><input type="number" class="form-control" id="total_fee" name="total_fee" value="" disabled>
</div>
</div>
</div>
<hr/>
<div class="row">
<div class="col-xl-2">
<div class="form-group">
<label class="gr"><b>Payment by Cash:</b></label><input type="number" class="form-control" name="paid_cash" id="paid_cash" placeholder="0" min="0">
</div>
</div>
<div class="col-xl-2">
<div class="form-group">
<label class="gr"><b>GPay Payment:</b></label><input type="number" class="form-control" id="paid_gpay" name="paid_gpay" placeholder="0" min="0">
</div>
</div>
<div class="col-xl-2">
<div class="form-group">
<label class="gr"><b>UPI Payment:</b></label><input type="number" class="form-control" id="paid_upi" name="paid_upi" placeholder="0" min="0">
</div>
</div>
<div class="col-xl-2">
<div class="form-group">
<label class="gr"><b>Card Payment:</b></label><input type="number" class="form-control" name="paid_card" id="paid_card" placeholder="0" min="0">
</div>
</div>
<div class="col-xl-2">
<div class="form-group">
<label class="gr"><b>Other Payment:</b></label><input type="number" class="form-control" name="paid_others" id="paid_others" placeholder="0" min="0">
</div>
</div>
<div class="col-xl-2">
<div class="form-group">
<label class="gr"><b>Total Paid Payment:</b></label><input type="number" class="form-control" id="total_fee_paid" name="total_fee_paid" value="" disabled>
</div>
</div>
</div>
<div class="row">
<div class="col-xl-12">
<div class="form-group">
<center>
<div id="error" class='error-text'>Test</div>
</center><br/><br/>
</div>
</div>
</div>
<div class="form-group text-right">
<button id="btnSubmit" type="submit" class="btn btn-primary float-end ">Add Visit</button>
</div>
</body>
</html>
Your logic seems good, but you call getElementById before DOM is ready, which means all elements are not available, and you try to call addEventListener to undefined elements.
To avoid that situation, you can add
$(document).ready(() => { //your logic })
Side note that I also improved your logic in validatePrices.
<html>
<head>
<!-- CSS only -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.2.0/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-gH2yIJqKdNHPEq0n4Mqa/HGKIhSkIHeL5AyhkYV8i59U5AR6csBvApHHNl/vI1Bx" crossorigin="anonymous">
<!-- JavaScript Bundle with Popper -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.2.0/dist/js/bootstrap.bundle.min.js" integrity="sha384-A3rJD856KowSb7dwlZdYEkO39Gagi7vIsF0jrRAoQmDKKtQBHUuLZ9AsSv4jD4Xa" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js" integrity="sha512-894YE6QWD5I59HgZOGReFYm4dnWc1Qt5NtvYSaNcOP+u1T9qYdvdihz0PPSiiqn/+/3e7Jo4EaG7TubfWGUrMQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<style>
.error-text {
font-size: 14px;
color: red;
margin-top: 15px;
}
</style>
<!-- Total Receiving Fee Calculation from Cash, Gpay, UPI, Card, Others -->
<script type="text/javascript">
$(function() {
const paid_cash = document.getElementById("paid_cash");
const paid_gpay = document.getElementById("paid_gpay");
const paid_upi = document.getElementById("paid_upi");
const paid_card = document.getElementById("paid_card");
const paid_others = document.getElementById("paid_others");
const total_fee_paid = document.getElementById("total_fee_paid");
paid_cash.addEventListener("input", sum);
paid_gpay.addEventListener("input", sum);
paid_upi.addEventListener("input", sum);
paid_card.addEventListener("input", sum);
paid_others.addEventListener("input", sum);
function sum() {
total_fee_paid.value = Number(paid_cash.value) + Number(paid_gpay.value) + Number(paid_upi.value) + Number(paid_card.value) + Number(paid_others.value);
}
});
</script>
<!-- Total Fee Calculation from Consultation fee and Other fee-->
<script type="text/javascript">
$(function() {
const fee1 = document.getElementById("visit_cons_fee");
const fee2 = document.getElementById("visit_other_fee");
const total_fee = document.getElementById("total_fee");
fee1.addEventListener("input", sum);
fee2.addEventListener("input", sum);
function sum() {
total_fee.value = Number(fee1.value) + Number(fee2.value);
}
});
</script>
<script type="text/javascript">
$(document).ready(() => {
// access the button from the html
const btn = document.getElementById("btnSubmit");
// access input boxes total_fee, total_fee_paid
const [visit_cons_fee, visit_other_fee, paid_cash, paid_gpay, paid_upi, paid_card, paid_others] = [
document.getElementById("visit_cons_fee"),
document.getElementById("visit_other_fee"),
document.getElementById("paid_cash"),
document.getElementById("paid_gpay"),
document.getElementById("paid_upi"),
document.getElementById("paid_card"),
document.getElementById("paid_others")
];
const total_fee = document.getElementById("total_fee");
const total_fee_paid = document.getElementById("total_fee_paid");
// a generic method to validate if prices indicate
// that 'submit' button should be disabled
// as well as render an error notification
const validatePrices = () => {
const invalid = Number(total_fee.value) < Number(total_fee_paid.value);
btn.disabled = invalid;
document.getElementById("error").innerText = invalid ?
'Sum of Receiving Payment exceeds Total Fee, Please Check!' :
''
};
// add event-listener to each input to invoke the validate method
[visit_cons_fee, visit_other_fee, paid_cash, paid_gpay, paid_upi, paid_card, paid_others].forEach(
(item) => {
item.addEventListener('keyup', validatePrices)
});
})
</script>
</head>
<body>
<div class="row">
<div class="col-xl-4">
<div class="form-group">
<label class="gr"><b>Consulation Fees:</b><span class="text-danger">*</span></label><input type="number" class="form-control" id="visit_cons_fee" name="visit_cons_fee" required min="0">
</div>
</div>
<div class="col-xl-4">
<div class="form-group">
<label class="gr"><b>Other Charges:</b></label><input type="number" class="form-control" id="visit_other_fee" name="visit_other_fee" min="0">
</div>
</div>
<div class="col-xl-4">
<div class="form-group">
<label class="gr"><b>Total Fee:</b></label><input type="number" class="form-control" id="total_fee" name="total_fee" value="" disabled>
</div>
</div>
</div>
<hr />
<div class="row">
<div class="col-xl-2">
<div class="form-group">
<label class="gr"><b>Payment by Cash:</b></label><input type="number" class="form-control" name="paid_cash" id="paid_cash" placeholder="0" min="0">
</div>
</div>
<div class="col-xl-2">
<div class="form-group">
<label class="gr"><b>GPay Payment:</b></label><input type="number" class="form-control" id="paid_gpay" name="paid_gpay" placeholder="0" min="0">
</div>
</div>
<div class="col-xl-2">
<div class="form-group">
<label class="gr"><b>UPI Payment:</b></label><input type="number" class="form-control" id="paid_upi" name="paid_upi" placeholder="0" min="0">
</div>
</div>
<div class="col-xl-2">
<div class="form-group">
<label class="gr"><b>Card Payment:</b></label><input type="number" class="form-control" name="paid_card" id="paid_card" placeholder="0" min="0">
</div>
</div>
<div class="col-xl-2">
<div class="form-group">
<label class="gr"><b>Other Payment:</b></label><input type="number" class="form-control" name="paid_others" id="paid_others" placeholder="0" min="0">
</div>
</div>
<div class="col-xl-2">
<div class="form-group">
<label class="gr"><b>Total Paid Payment:</b></label><input type="number" class="form-control" id="total_fee_paid" name="total_fee_paid" value="" disabled>
</div>
</div>
</div>
<div class="row">
<div class="col-xl-12">
<div class="form-group">
<center>
<div id="error" class='error-text'>Test</div>
</center><br /><br />
</div>
</div>
</div>
<div class="form-group text-right">
<button id="btnSubmit" type="submit" class="btn btn-primary float-end ">Add Visit</button>
</div>
</body>
</html>
Here is a jQuery specific approach, it is a rework, but only because you are already loading the library. The only slight modifications to HTML being adding a class for payment specific fields as well as fee specific fields. This is a little more concise and readable, but ultimately, it is just another approach.
<html>
<head>
<!-- CSS only -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.2.0/dist/css/bootstrap.min.css" rel="stylesheet"
integrity="sha384-gH2yIJqKdNHPEq0n4Mqa/HGKIhSkIHeL5AyhkYV8i59U5AR6csBvApHHNl/vI1Bx" crossorigin="anonymous">
<!-- JavaScript Bundle with Popper -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.2.0/dist/js/bootstrap.bundle.min.js"
integrity="sha384-A3rJD856KowSb7dwlZdYEkO39Gagi7vIsF0jrRAoQmDKKtQBHUuLZ9AsSv4jD4Xa"
crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"
integrity="sha512-894YE6QWD5I59HgZOGReFYm4dnWc1Qt5NtvYSaNcOP+u1T9qYdvdihz0PPSiiqn/+/3e7Jo4EaG7TubfWGUrMQ=="
crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<style>
.error-text {
font-size: 14px;
color: red;
margin-top: 15px;
}
</style>
</head>
<body>
<div class="container mt-5">
<div class="row">
<div class="col-xl-4">
<div class="form-group">
<label class="gr"><b>Consulation Fees:</b><span class="text-danger">*</span></label><input type="number"
class="form-control field-consult-fee" id="visit_cons_fee" name="visit_cons_fee" required min="0">
</div>
</div>
<div class="col-xl-4">
<div class="form-group">
<label class="gr"><b>Other Charges:</b></label><input type="number" class="form-control field-consult-fee"
id="visit_other_fee" name="visit_other_fee" min="0">
</div>
</div>
<div class="col-xl-4">
<div class="form-group">
<label class="gr"><b>Total Fee:</b></label><input type="number" class="form-control" id="total_fee"
name="total_fee" value="" disabled>
</div>
</div>
</div>
<hr />
<div class="row">
<div class="col-xl-2">
<div class="form-group">
<label class="gr"><b>Payment by Cash:</b></label><input type="number" class="form-control field-payment-type"
name="paid_cash" id="paid_cash" placeholder="0" min="0">
</div>
</div>
<div class="col-xl-2">
<div class="form-group">
<label class="gr"><b>GPay Payment:</b></label><input type="number" class="form-control field-payment-type"
id="paid_gpay" name="paid_gpay" placeholder="0" min="0">
</div>
</div>
<div class="col-xl-2">
<div class="form-group">
<label class="gr"><b>UPI Payment:</b></label><input type="number" class="form-control field-payment-type"
id="paid_upi" name="paid_upi" placeholder="0" min="0">
</div>
</div>
<div class="col-xl-2">
<div class="form-group">
<label class="gr"><b>Card Payment:</b></label><input type="number" class="form-control field-payment-type"
name="paid_card" id="paid_card" placeholder="0" min="0">
</div>
</div>
<div class="col-xl-2">
<div class="form-group">
<label class="gr"><b>Other Payment:</b></label><input type="number" class="form-control field-payment-type"
name="paid_others" id="paid_others" placeholder="0" min="0">
</div>
</div>
<div class="col-xl-2">
<div class="form-group">
<label class="gr"><b>Total Paid Payment:</b></label><input type="number" class="form-control"
id="total_fee_paid" name="total_fee_paid" value="" disabled>
</div>
</div>
</div>
<div class="row">
<div class="col-xl-12">
<div class="form-group text-center mb-4">
<div id="error" class='error-text'>Test</div>
</div>
</div>
</div>
<div class="form-group text-right">
<button id="btnSubmit" type="submit" class="btn btn-primary float-end ">Add Visit</button>
</div>
</div>
<script>
$(document).ready(function () {
// store our payment fields in variables
const $paid_cash = $("#paid_cash")
const $paid_gpay = $("#paid_gpay")
const $paid_upi = $("#paid_upi")
const $paid_card = $("#paid_card")
const $paid_others = $("#paid_others")
// store our fee fields in variables
const $fee1 = $("#visit_cons_fee")
const $fee2 = $("#visit_other_fee")
const $total_fee = $("#total_fee")
// store our totals in variables
const $total_fee_paid = $("#total_fee_paid")
const $field_payment_type = $("input.field-payment-type")
// function to sum our payment fields and display the total
function sumPayments() {
const payment_fields = [$paid_cash, $paid_gpay, $paid_upi, $paid_card, $paid_others]
const total_fee_paid = payment_fields.reduce((a, b) => a + +b.val(), 0)
$total_fee_paid.val(total_fee_paid)
validate()
}
// function to sum our fee fields and display the total
function sumFees() {
const fee_fields = [$fee1, $fee2];
const total_fee = fee_fields.reduce((a, b) => a + +b.val(), 0)
$total_fee.val(total_fee)
validate()
}
// function to validate our payment does not exceed our fee
function validate() {
const $btn_submit = $("#btnSubmit")
const total_fee = +$total_fee.val()
const total_fee_paid = +$total_fee_paid.val()
let disabled = false
let error = " "
if (total_fee_paid > total_fee) {
error = "Total paid amount cannot be greater than total fee"
disabled = true
}
$("#error").html(error)
$btn_submit.attr("disabled", disabled)
}
// add event listeners to our payment_type fields
$field_payment_type.on('input', sumPayments)
$field_consult_fee.on('input', sumFees)
});
</script>
</body>
</html>

OnClick Solve equation

I'm trying to create a simple html page that would have three input variables (A,B,C). Once the user has provided these values they will press "calculate", and the JavaScript will run the values through the following equations
((A + B)/2) * 3 = X
and
(C * 2) = Y
The answers will appear as outputs of X Value and Y Value.
Here is an image:
I have written the HTML but i'm having difficulty with the JavaScript. Could someone please help :) Thank you so much in advance!
<!DOCTYPE html>
<html >
<head>
<meta charset="UTF-8">
<title>Example</title>
</head>
<body>
<body class="container">
<div class="row">
<div class="span6">
<h1 align="center">Example</h1>
<form class="form-horizontal well w3-center" style="max-width: 850px; width: 100%; margin: 0 auto;">
<div class="control-group">
<label class="control-label">A</label>
<div class="controls">
<input type="text" name="A" class="ratecalcfield"></input>
</div>
</div>
<div class="control-group">
<label class="control-label">B</label>
<div class="controls">
<input type="text" name="B" class="ratecalcfield"></input>
</div>
</div>
<div class="control-group">
<label class="control-label">C</label>
<div class="controls">
<input type="text" name="C" class="ratecalcfield"></input>
</div>
</div>
<div class="control-group">
<label class="control-label">X Value</label>
<div class="controls">
<input type="text" name="x" class="ratecalcfield"></input>
</div>
</div>
<div class="control-group">
<label class="control-label">Y Value</label>
<div class="controls">
<input type="text" name="y" class="ratecalcfield"></input>
</div>
</div>
<div class="control-group w3-margin-top">
<div class="controls">
<input type="button" class="w3-button w3-blue w3-padding-large" style="max-width: 200px; width: 100%;" onclick="cmdCalc_Click()" value="Calculate" name="cmdCalc"></input>
</div>
</div>
</form>
<script src="js/index.js"></script>
</body>
</html>
function cmdCalc_Click() {
calculate();
}
function calculate() {
A = parseInt(document.getElementById("A").value);
B = parseInt(document.getElementById("B").value);
C = parseInt(document.getElementById("C").value);
x = document.getElementById("x");
y = document.getElementById("y");
x.innerHTML = (3 * C);
y.innerHTML = (((A + B) / 2 ) * 2));
}
See here.
I have appended to each input an unique id. After that I have got the elements in JavaScript via document.getElementById. Each element has a value property which holds the value of the input element. On the click event, I get the values of A, B and C and calculates them. After calculation I set the values to X and Y.
var a = document.getElementById('A');
var b = document.getElementById('B');
var c = document.getElementById('C');
var x = document.getElementById('X');
var y = document.getElementById('Y');
function cmdCalc_Click(){
x.value = ((Number.parseInt(a.value) + Number.parseInt(b.value)) / 2) * 3
y.value = c.value * 2;
}
<form class="form-horizontal well w3-center" style="max-width: 850px; width: 100%; margin: 0 auto;">
<div class="control-group">
<label class="control-label">A</label>
<div class="controls">
<input id="A" type="text" name="A" class="ratecalcfield">
</div>
</div>
<div class="control-group">
<label class="control-label">B</label>
<div class="controls">
<input id="B" type="text" name="B" class="ratecalcfield">
</div>
</div>
<div class="control-group">
<label class="control-label">C</label>
<div class="controls">
<input id="C" type="text" name="C" class="ratecalcfield">
</div>
</div>
<div class="control-group">
<label class="control-label">X Value</label>
<div class="controls">
<input id="X" type="text" name="x" class="ratecalcfield">
</div>
</div>
<div class="control-group">
<label class="control-label">Y Value</label>
<div class="controls">
<input id="Y" type="text" name="y" class="ratecalcfield">
</div>
</div>
<div class="control-group w3-margin-top">
<div class="controls">
<input type="button" class="w3-button w3-blue w3-padding-large" style="max-width: 200px; width: 100%;" onclick="cmdCalc_Click()" value="Calculate" name="cmdCalc">
</div>
</div>
</form>
It's not necessary use "id" in the variable fields, just get them through the field name using getElementsByName ('inputNameHere')[0].value)
function cmdCalc_Click(){
var a = Number.parseInt(document.getElementsByName('A')[0].value);
var b = Number.parseInt(document.getElementsByName('B')[0].value);
var c = Number.parseInt(document.getElementsByName('C')[0].value);
var x = Number.parseInt(document.getElementsByName('X')[0].value);
var y = Number.parseInt(document.getElementsByName('Y')[0].value);
e1 = ((a + b)/2) * 3
if(e1 == x && x != 0){
alert("Correct " + e1 + " is equal to " + x);
}
e2 = (c * 2)
if(e2 == y && y != 0){
alert("Correct" + e2 + " is equal to " + y);
}
}
all html error corrected.
forces inputs to be number (avoid unnecessary parseInt in js).
set a class to work with.
make the calculation.
set new x and y values.
<!DOCTYPE html>
<html >
<head>
<meta charset="UTF-8">
<title>Example</title>
</head>
<body>
<div class="container">
<div class="row">
<div class="span6">
<form class="form-horizontal well w3-center" style="max-width: 850px; width: 100%; margin: 0 auto;">
<div class="control-group">
<label class="control-label">A</label>
<div class="controls">
<input type="number" id="A" class="ratecalcfield">
</div>
</div>
<div class="control-group">
<label class="control-label">B</label>
<div class="controls">
<input type="number" id="B" class="ratecalcfield">
</div>
</div>
<div class="control-group">
<label class="control-label">C</label>
<div class="controls">
<input type="number" id="C" class="ratecalcfield">
</div>
</div>
<div class="control-group">
<label class="control-label">X Value</label>
<div class="controls">
<input type="number" id="x" class="ratecalcfield">
</div>
</div>
<div class="control-group">
<label class="control-label">Y Value</label>
<div class="controls">
<input type="number" id="y" class="ratecalcfield">
</div>
</div>
<div class="control-group w3-margin-top">
<div class="controls">
<input type="button" class="w3-button w3-blue w3-padding-large" style="max-width: 200px; width: 100%;" onclick="cmdCalc_Click()" value="Calculate" name="cmdCalc">
</div>
</form>
</div>
</div>
</div>
</body>
<script>
function cmdCalc_Click() {
let x = document.getElementById("x");
let y = document.getElementById("y");
const Preset = new whatToDo(x, y);
const result = Preset.calculate();
x.value = result.x;
y.value = result.y;
}
class whatToDo {
constructor(x, y) {
this.A = (document.getElementById("A").value);
this.B = (document.getElementById("B").value);
this.C = (document.getElementById("C").value);
}
calculate() {
return {
x: (3 * this.C),
y: (((this.A + this.B) / 2) * 2)
}
}
}
</script>
</body>
</html>
You can use the JavaScript eval function to calculate any expression.
function cmdCalc_Click() {
var a = document.querySelector('[name=A]').value;
var b = document.querySelector('[name=B]').value;
var c = document.querySelector('[name=C]').value;
var x = document.querySelector('[name=x]');
var y = document.querySelector('[name=y]');
x.value = eval("((" + a + " + " + b + ")/2) * 3");
y.value = eval("(" + c + " * 2)");
}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Example</title>
</head>
<body class="container">
<div class="row">
<div class="span6">
<h1 align="center">Example</h1>
<form class="form-horizontal well w3-center" style="max-width: 850px; width: 100%; margin: 0 auto;">
<div class="control-group">
<label class="control-label">A</label>
<div class="controls">
<input type="text" name="A" class="ratecalcfield">
</div>
</div>
<div class="control-group">
<label class="control-label">B</label>
<div class="controls">
<input type="text" name="B" class="ratecalcfield">
</div>
</div>
<div class="control-group">
<label class="control-label">C</label>
<div class="controls">
<input type="text" name="C" class="ratecalcfield">
</div>
</div>
<div class="control-group">
<label class="control-label">X Value</label>
<div class="controls">
<input type="text" name="x" class="ratecalcfield">
</div>
</div>
<div class="control-group">
<label class="control-label">Y Value</label>
<div class="controls">
<input type="text" name="y" class="ratecalcfield">
</div>
</div>
<div class="control-group w3-margin-top">
<div class="controls">
<input type="button" class="w3-button w3-blue w3-padding-large" style="max-width: 200px; width: 100%;" onclick="cmdCalc_Click()" value="Calculate" name="cmdCalc">
</div>
</div>
</form>
</div>
</div>
</body>
</html>
The problem with your code is that you didnt add the A, B, C, X, and Y Ids to each form fields and you are using innerHTML to set form value for X and Y.
X & Y is a text field and you should set the values as
X.value=(3*C);
Y.value=((A+B)/2);
Set the ids that you are referencing in javascript to the appropraite text fields like:
<input type="text" id="A" name="A" class="">
etc.
now the document.getElementById("A"); can find the field with id A and get its value.
Another problem:
Using value to set the value of an textfield not innerHTML
Also modify your onclick event with the below code so you wont have the for submitted and the page loaded.
onclick="cmdCal_Click(); return false"

does not show error in my captcha code as security code does not match

<div class="row">
<div class="form-group">
<label class="control-label col-sm-6"><i>*</i> Address</label>
<div class="col-sm-3">
<input id="address" class="address" type="text" name="address"
onchange="IsValidAddress(this.form.address.value)" required="required" >
</div>
<div class="col-sm-3">
</div>
</div>
</div>
<div> </div>
<div class="row">
<div class="form-group">
<label class="control-label col-sm-6"><i>*</i> Zip Code :</label>
<div class="col-sm-3">
<input id="zipcode" class="zipcode" type="text" name="zipcode" onchange="IsValidZipCode(this.form.zipcode.value)" required="required" >
<br />
</div>
<div class="col-sm-3">
</div>
</div>
</div>
<div> </div>
<div class="row">
<div class="form-group">
<label class="control-label col-sm-6"><i>*</i> City</label>
<div class="col-sm-3">
<input class="form-control" name="city" type="text" id="city" required="required" value="">
</div>
<div class="col-sm-3">
</div>
</div>
</div>
<div> </div>
<div class="row">
<div class="form-group">
<label class="control-label col-sm-6"><i>*</i> State</label>
<div class="col-sm-3">
<input class="form-control" name="state" type="text" id="state" value="" required ="required">
</div>
<div class="col-sm-3">
</div>
</div>
</div>
<div> </div>
<div class="row">
<div class="form-group">
<label class="control-label col-sm-6"><i>*</i> Country</label>
<div class="col-sm-3">
<input class="form-control" name="country" type="text" id="country" value="" required="required">
</div>
<div class="col-sm-3">
</div>
</div>
</div>
<div> </div>
<div class="row">
<div class="form-group">
<label class="control-label col-sm-6"> Fax</label>
<div class="col-sm-3">
<input class="form-control" name="fax" type="text" id="fax" value="" required ="required">
</div>
<div class="col-sm-3">
</div>
</div>
</div>
<div> </div>
<div class="row">
<div class="form-group">
<label class="control-label col-sm-6"><i>*</i> Captcha</label>
<div class="col-sm-2">
</div>
<div class="col-sm-3">
<form name="review" ACTION="playing-cards-quote.php" METHOD="POST" onsubmit="return checkform(this);">
<font color="#DD0000"></font> <span id="txtCaptchaDiv" style="background-color:#A51D22;color:#FFF;padding:5px"></span>
<input type="hidden" id="txtCaptcha" />
<input type="text" name="txtInput" id="txtInput" size="15" />
<input type="submit" value="Submit" class="btn1" name="submit" id="send">
</form>
<script type="text/javascript">
function checkform(theform){
var why = "";
if(theform.txtInput.value == ""){
why += "- Security code should not be empty.\n";
}
if(theform.txtInput.value != ""){
if(ValidCaptcha(theform.txtInput.value) == false){
why += "- Security code did not match.\n";
}
}
if(why != ""){
alert(why);
return false;
}
}
//Generates the captcha function
var a = Math.ceil(Math.random() * 9)+ '';
var b = Math.ceil(Math.random() * 9)+ '';
var c = Math.ceil(Math.random() * 9)+ '';
var d = Math.ceil(Math.random() * 9)+ '';
var e = Math.ceil(Math.random() * 9)+ '';
var code = a + b + c + d + e;
document.getElementById("txtCaptcha").value = code;
document.getElementById("txtCaptchaDiv").innerHTML = code;
// Validate the Entered input aganist the generated security code function
function ValidCaptcha(){
var str1 = removeSpaces(document.getElementById('txtCaptcha').value);
var str2 = removeSpaces(document.getElementById('txtInput').value);
if (str1 == str2){
return true;
}else{
return false;
}
}
// Remove the spaces from the entered and generated code
function removeSpaces(string){
return string.split(' ').join('');
}
</script>
</div>
<div class="col-sm-3">
</div>
</div>
<div> </div>
<div class="row">
<div class="form-group">
<div class="col-sm-12">
<center>
</center>
</div>
</div>
</div>
<div> </div>
</div>
</fieldset>
</form>
</div>
</div>
</div>
<!---footer---><?php include("include files/footer.php");?>
</body>
</html>
my javascript code is written above html code but in this code i m writing below html code ......
does it effect my calling my function of captcha
does not show me error like security does not match?
if i click n submit button it redirect me to the thank you page
what is the problem with captcha validation
why it is not validation the match not done correctly
why it is directly accepting the form without validating the capctha?
what is the problem n the code?
cannot identify the error pease help me

Sending jQuery UI Slider value though a form

I'm using the jQuery UI Slider in a form that should submit the information to Velocify.
Everything gets sent correctly but the slider's value stays blank. Here is my code:
<form id="short-form" name="short-form" method="post" data-toggle="validator" role="form"
action="https://secure.velocify.com/Import.aspx?Provider=XXXXX&Client=XXXXX&CampaignId=XXXXX&URL=https://example.com/confirmation.php">
<input type="hidden" name="keyword" id="keyword" />
<div class="form-group">
<label class="loan-amount-label" for="_Requested_loan_amount">I'd like to borrow:</label>
<input type="text" id="_Requested_loan_amount" name="_Requested_loan_amount" class="loan-amount" readonly>
<p class="small">Drag the slider below to the amount you'd like to borrow</p>
<div id="slider"></div>
<div class="row slider-minmax">
<div class="col-xs-6 col-sm-6 col-md-6 text-left min">$2,501</div>
<div class="col-xs-6 col-sm-6 col-md-6 text-right max">$50,000</div>
</div>
</div>
<div class="row">
<div class="col-sm-6 col-md-6 form-group">
<label for="_First_name" class="hidden">First Name</label>
<input type="text" class="form-control" id="_First_name" name="_First_name"
placeholder="First Name *" data-error="Please enter your first name." required>
</div>
<div class="col-sm-6 col-md-6 form-group">
<label for="_Last_name" class="hidden">Last Name</label>
<input type="text" class="form-control" id="_Last_name" name="_Last_name"
placeholder="Last Name *" data-error="Please enter your last name." required>
</div>
</div>
<div class="row">
<div class="col-sm-6 col-md-6 form-group">
<label for="_Home_Phone" class="hidden">Phone Number</label>
<input type="text" class="form-control" id="_Home_Phone" name="_Home_Phone"
placeholder="Your Phone Number *" data-error="Please enter a valid phone number." required>
</div>
<div class="col-sm-6 col-md-6 form-group">
<label for="_Email_Address" class="hidden">Email</label>
<input type="email" class="form-control" id="_Email_Address" name="_Email_Address"
placeholder="Your Email *" data-error="Please enter a valid email address." required>
</div>
</div>
<div class="row">
<div class="col-sm-6 col-md-6 form-group">
<label for="_Auto_year">Vehicle Year:</label>
<select class="form-control" id="_Auto_year" name="_Auto_year"
data-error="Please choose a vehicle year." required>
</select>
</div>
<div class="col-sm-6 col-md-6 form-group">
<label for="_Auto_make">Vehicle Make:</label>
<select class="form-control" id="_Auto_make" name="_Auto_make"
data-error="Please choose a vehicle make." required>
</select>
</div>
</div>
<div class="row">
<div class="col-md-12">
<hr>
</div>
</div>
<div class="row">
<div class="col-xs-7 col-sm-8 col-md-8 form-group">
<button type="submit" class="btn btn-primary btn-lg btn-block">
Get Started
</button>
</div>
<div class="col-xs-5 col-sm-4 col-md-4">
<div class="verify pull-right text-right">
</div>
</div>
</div>
</form>
The javascript:
<script>
$(function () {
$("#slider").slider({
value: 6500,
min: 2501,
max: 50500,
step: 500,
range: "min",
slide: function(event, ui) {
var x = Number(ui.value);
if (x > 2501) {
x = x - (x % 500);
}
$("#_Requested_loan_amount").val('$' + addCommas(x));
}
});
$("#_Requested_loan_amount").val('$' + addCommas($("#slider").slider("value")));
function addCommas(nStr) {
var x = Number(nStr);
if (x > 2501) {
x = x - (x % 500);
}
nStr = x.toString();
x = nStr.split('.');
x1 = x[0];
x2 = x.length > 1 ? '.' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + ',' + '$2');
}
return x1 + x2;
}
});
</script>
When I submit the form to my test page using
<?php echo $_POST["_Requested_loan_amount"]; ?>
I see the field value generates correctly so I'm not sure why it isn't sending that value to Velocify.
Thanks!

Categories

Resources