Get form fields to hide and populate - javascript

I have a 3 fields:
Total amount
Recurring amount
Occurrences
A user will always enter occurrences, but has the choice of entering either total amount or recurring amount.
The equation for this is really simple:
Occurrences * Recurring Amount = Total Amount
I need help making a Javascript function which if the user starts to type in the total amount field, recurring amount becomes disabled. The same is true if they enter recurring amount first. Once the user has input occurrences and either of the amounts, the remaining amount should be calculated and replace the disabled field.
I need the function to be able to allow the user to change any of the numbers, and have the calculation be re-done. Also, if the user totally removes a value from an amount, the other amount field should become active again.
I've never written Javascript code before, only edited. Any help to point me in the right direction is appreciated. Thanks

Not sure why you think disabling fields is a good idea. I think user experience-wise it would be better to allow them to edit any field at any time, adjusting the other fields as needed.
<input id="recurring" onchange="onRecurEdit()"> *
<input id="occurences" onchange="onOccurEdit()"> =
<input id="total" onchange="onTotalEdit()">
<script>
var recur = document.getElementById('recurring');
var total = document.getElementById('total');
var occur = document.getElementById('occurences');
function onTotalEdit() {
recurring.value = total.value / occur.value;
}
function onRecurEdit() {
total.value = occur.value * recur. value;
}
function onOccurEdit() {
total.value = occur.value * recur. value;
}
</script>

Here's partly what you may be looking for: The code uses JQuery
JS code:
$(document).ready(function() {
function roundNumber(num, dec) {
var result = Math.round(num*Math.pow(10,dec))/Math.pow(10,dec);
return result;
}
function calculateTot(evt) {
var o = Number($("#occur").val());
var a = Number($("#recAmt").val());
if(!isNaN(0) && !isNaN(a)) {
var tot = roundNumber(o * a, 2);
$("#totalAmt").val(tot);
}else {
$("#totalAmt").val("0");
}
}
$("#occur").bind("change", calculateTot);
$("#recAmt").bind("change", calculateTot);
});
HTML for the same:
<input type="text" id="occur" /> *
<input type="text" id="recAmt" /> =
<input type="text" id="totalAmt" readonly="readonly" />

This won't be perfect but it should be a decent start:
You can view an interactive demo of this code at http://jsfiddle.net/qzxf7/
You haven't given us your HTML so I'm going to assume you're using something like this:
<form action="" method="POST">
<input type="text" name="occurences" id="occurences" value="" />
<input type="text" name="recurringAmt" id="recurringAmt" value="" />
<input type="text" name="totalAmt" id="totalAmt" value="" />
</form>
If you haven't dealt with Javascript before, I'm going to recommend you use jQuery which is a matter of importing the jQuery script in your HTML <head>.
Using jQuery you could start with code like this which is overly complicated but throws you into how to handle the disabled stuff as well as value updates.
/* On page contents loaded */
function updateForm() {
var occ = $('#occurences');
var occV = parseFloat(occ.val());
occV = occV >= 0 ? occV : 0;
var rec = $('#recurringAmt');
var recV = parseFloat(rec.val());
recV = recV >= 0 ? recV : 0;
var tot = $('#totalAmt');
var totV = parseFloat(tot.val());
totV = totV >= 0 ? totV : 0;
/* If total is disabled */
if (tot.attr("disabled")) {
if (rec.val() == '') { /* if no text in rec */
tot.removeAttr("disabled"); /* Reenable total */
tot.val('');
return;
}
/* Otherwise update total */
tot.val(recV * occV);
return;
}
/* If rec is disabled */
if (rec.attr("disabled")) {
if (tot.val() == '') { /* if no text in total */
rec.removeAttr("disabled"); /* Reenable rec */
rec.val('');
return;
}
/* Otherwise update rec watching for divide by zero error */
rec.val(occV > 0 ? totV / occV : 0);
return;
}
/* Otherwise neither disabled */
if (recV > 0) { /* if rec has a number value */
tot.attr("disabled", true); /* disable total */
tot.val(recV * occV); /* update total */
return;
}
if (totV > 0) { /* if total has a number value */
rec.attr("disabled", true); /* disable rec */
/* Update rec watching for divide by zero error */
rec.val(occV > 0 ? totV / occV : 0);
return;
}
}
$(document).ready(function() {
$('#occurences').keyup(function(){
updateForm();
});
$('#totalAmt').keyup(function(){
updateForm();
});
$('#recurringAmt').keyup(function(){
updateForm();
});
});

Related

On keyup is not satisfying the condition

<label> Telugu</label>
<input type="text" onkeyup="return isNumber(event)" name="telugu" id="telugu" maxlength="3"/> <br> <br>
JS
<!DOCTYPE html>
<html>
<head>
<script>
function isNumber(event){
var k= event.keyCode;
console.log(k);
if((k>47 && k<58)) /// THIS IS NOT WORKING
{
console.log("entered");
var s1 = document.getElementById("telugu").value;
var s2= document.getElementById("hindi").value;
var s3= document.getElementById("english").value;
var s4= document.getElementById("maths").value;
var s5= document.getElementById("science").value;
if(s1<0 || s1>100){
console.log("tel")
document.getElementById("telugu").value = 0;
}
I want to input only numbers in a textbox. the condition is not working. If the value in the textbox is less than 0 or greater than 100. then I am resetting the value to 0. Resetting is working but the characters are also entering.
You could use a regex to remove everything that is not a digit. I also change to the input event which fires whenever the input changes.
If you want to force numbers you could also just set the type to type="number". The benefit for this is that it will automatically show the number keyboard on phones and tablets, though you can show this as well with the inputmode="numeric" attribute
// Get the textbox
const telugu = document.getElementById("telugu");
// Add event that fires whenever the input changes
telugu.addEventListener("input", () => {
// Replace everything that is not a digit with nothing
const stripped = telugu.value.replace(/[^\d]/g, "");
// If the value is below 0 or above 100 set it to 0, else enter the stripped value
stripped < 0 || stripped > 100
? telugu.value = 0
: telugu.value = stripped;
});
<label for="telugu">Telugu</label>
<input type="text" name="telugu" id="telugu" maxlength="3"/>
Without comments:
const telugu = document.getElementById("telugu");
telugu.addEventListener("input", () => {
const stripped = telugu.value.replace(/[^\d]/g, "");
stripped < 0 || stripped > 100
? telugu.value = 0
: telugu.value = stripped;
});
<label for="telugu">Telugu</label>
<input type="text" name="telugu" id="telugu" maxlength="3"/>
Simplified:
function validateValue(event) {
var input = event.target;
var stripped = input.value.replace(/[^0-9]/g, ""); /* Everthing that is not (^) in the range of 0 through 9 */
if(stripped < 0 || stripped > 100) {
input.value = 0;
} else {
input.value = stripped;
}
}
<label for="telugu">Telugu</label>
<input type="text" oninput="validateValue(event)" name="telugu" id="telugu" maxlength="3"/>
You should do s1 variable parsed integer with parseInt() function.
function isNumber(event){
var k = event.keyCode;
console.log(k);
if(k>47 && k<58){
console.log("entered");
var s1 = parseInt(document.getElementById("telugu").value);
console.log('s1', s1);
if(s1<0 || s1>100){
console.log("tel")
document.getElementById("telugu").value = 0;
}
}else{
document.getElementById("telugu").value = null;
}
}
<label> Telugu</label>
<input type="text" onkeyup="return isNumber(event)" name="telugu" id="telugu" maxlength="3"/>
There are different ways to to this.
input: Fires when the value of the input has changed.
change: Fires when the value of the input has changed and the element loses its focus (it is no more selected).
blur: Fires when the input losed its focus.
Which event you use, depend on when you want to check the input. Use input if you want to check it instantly after the change of the value. Otherwise use blur or change.
Example:
let input = document.querySelector('#telegu');
input.addEventListener('input', () => {
// Your check
});
input.addEventListener('change', () => {
// Your check
});
input.addEventListener('blur', () => {
// Your check
});

How to find the empty field and calculate the value for the missing field

I have a javascript application where I need to have a calculator for mortgages, the required UI looks like
The only issue is I cannot have the calculate button, so I have to verify the empty field and do the calculation, the initial calculation works successfully but if the user wants to delete a single field the value for the deleted field get filled automatically which I want to prevent, is there a way to achieve this?
Current Code
If condition
function checkForValues(){
if(this.state.loanAmount != 0 && this.state.noOfYears != 0 && this.state.interestRate != 0){
this.state.payment = this.state.loanAmount * ( (this.state.interestRate/12 * pow(1 + this.state.interestRate/12 , this.state.noOfYears) ) / ( pow(1 + this.state.interestRate/12 , this.state.noOfYears) - 1 ) )
}else if(this.state.payment != 0 && this.state.noOfYears != 0 && this.state.interestRate != 0){
this.state.loanAmount = this.state.payment / ( (this.state.interestRate/12 * pow(1 + this.state.interestRate/12 , this.state.noOfYears) ) / ( pow(1 + this.state.interestRate/12 , this.state.noOfYears) - 1 ) )
}
}
On change handler
onChange = e => {
this.setState({ [e.target.name]: e.target.value });
this.checkForValues();
};
<Label for='loanAmount'>Loan Amount</Label>
<Input
type='text'
name='loanAmount'
id='loanAmount'
className='mb-3'
placeholder='Loan Amount'
onChange={this.onChange}
/>
You can look at the field where the last change originated from and work out which field to update from there, e.g. (code abstracted from react so it runs here)
let pow = Math.pow;
let lastUpdatedByScript = null;
// Calc monthly payment based on formula at https://en.wikipedia.org/wiki/Mortgage_calculator
function checkForValues(e){
// Get elements of interest
let form = this.form;
let amountField = form.amount;
let paymentField = form.payment;
// Get values of interest
let amount = +amountField.value;
let years = +form.years.value;
let nPmnts = years * 12;
let rate = +form.rate.value / 100;
let mRate = rate / 12;
let payment = +paymentField.value;
// Work out field to update, if any
// If amount field changed, update payment
let fieldToChange = this == amountField? paymentField :
// If payment field changed, update amount
this == paymentField? amountField :
// If years or rate changed, update whichever of amount or payment
// was last changed by script (if either)
this == form.years || this == form.rate? lastUpdatedByScript : null;
// Only do something if have years and rate
if (years && rate) {
// Common factor, calc once
let f = mRate / (1 - (pow(1 + mRate, -nPmnts)));
// If changing payment field, calculate payment
if (fieldToChange == paymentField) {
paymentField.value = (amount * f).toFixed(2);
lastUpdatedByScript = paymentField;
// If change came from payment field, calculate amount
} else if (fieldToChange == amountField) {
amountField.value = (payment / f).toFixed(2);
lastUpdatedByScript = amountField;
}
}
}
document.querySelectorAll('input[type="number"]').forEach(inp => inp.addEventListener('change', checkForValues, false));
<form id="Calculator" onsubmit="return false;">
<table>
<tr><td>Term (years)<td>Rate (% pa)<td>Amount ($)<td>Monthly Payment ($)
<tr>
<td><input name="years" type="number" value="30">
<td><input name="rate" type="number" value="3.09">
<td><input name="amount" type="number">
<td><input name="payment" type="number">
<tr>
<td colspan="4"><input type="reset" value="Reset form">
</table>
</form>
You might also want to temporarily highlight the field changed by script to draw the user's attention to it, otherwise they may not see what happened. :-)

check condition before submitting form in jquery

I am submitting a frm that is basically an invoice of purchase. before submitting the form i want to implement the check that the user doesn't enter amount more than the total bill in the text box.for example if total bill is 300 and in the "paid amount" text box user enters 3000 accidentally then it should show the error message here is my code:
$("#mainform").submit(function() {
var total = $("#gtotal").val();
var paid = $("#paid").val();
alert(paid);
alert(total);
if(paid > total)
{
alert("Amount can't be greater than total");
return false;
}
return true;
});
when I alert paid and total amount they show correct values, but the if condition is not working some times it submits the form if the condition is not fulfilled sometimes i doesn't even condition is fulfilled
Try this, it may work:
var total = parseInt($("#gtotal").val());
var paid = parseInt($("#paid").val());
.val() returns strings
Convert paid and total to float with parseFloat, check them with isNaN, then compare. Like so:
paid = parseFloat(paid);
total = parseFloat(total);
if (!isNaN(paid) && !isNaN(total)) {
if (paid > total) {
...
If you aren't using decimals you may use parseInt
Add a parameter on submit function and call preventDefault method to avoid form to be submitted.
.submit(function(event) {
...
if (paid > total) {
...
event.preventDefault();
}
There are some conditions missed:
empty input field
not a number
In order to convert a string to number you can prefix the string with a plus sign.
A solution could be:
$("#mainform").on('submit', function(e) {
var total = +$("#gtotal").val();
var paid = +$("#paid").val();
if (($("#gtotal").val().trim().length == 0) || isNaN(total)) {
console.log("Please specify total");
$("#gtotal").focus();
e.preventDefault();
//
// stop function execution....
//
return;
}
if (($("#paid").val().trim().length == 0) || isNaN(paid)) {
console.log("Please specify paid");
$("#paid").focus();
e.preventDefault();
//
// stop function execution....
//
return;
}
if(paid > total) {
console.log("Amount can't be greater than total");
//
// prevent the submit action
//
re.preventDefault();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="mainform" action="http://www.google.com">
gtotal: <input id="gtotal" type="text">
paid:<input id="paid" type="text">
<input type="submit" value="Submit Form">
</form>

Currency converter doesn't work within a defined limit

I created a Bitcoin (BTC) to Canadian Dollar (CAD) converter that uses the current price from a different site, now I am trying to limit the values acceptable for the BTC/CAD inputs but it doesn't work.
The limits I want to set is $2 to $99.99 for CAD and the BTC equivalent for max/min but it doesn't want to work...
Fiddle:
https://jsfiddle.net/z735tswj/ all the relevant code is in the html tab or below
<input id="btcc" type="text" onkeyup="btcConvert()" onchange="btcCheck()">BTC</input>
<input id="cadc" type="text" onkeyup="cadConvert()" onchange="cadCheck()">CAD</input>
<br>
<br>
<script>
function btcConvert() {
var btc = document.getElementById("btcc").value;
var btcCalc = btc * price;
var btcCalc = btcCalc.toFixed(2);
document.getElementById("cadc").value = btcCalc;
btcCheck();
}
function cadConvert() {
var cad = document.getElementById("cadc").value;
var cadCalc = cad / price;
var cadCalc = cadCalc.toFixed(8);
document.getElementById("btcc").value = cadCalc;
cadCheck();
}
function btcCheck() {
if (btc.value < 0.001649) btc.value = 0.001649;
if (btc.value > 0.082259) btc.value = 0.082259;
btcConvert();
}
function cadCheck() {
if (cad.value < 2) cad.value = 2;
if (cad.value >= 100) cad.value = 99.99;
cadConvert();
}
</script>
Got it working, your script was not passing the input value to cadCheck()
I just made a few edits to get it to work. cadCheck() will get the value of the input before running cadConvert().
function cadCheck(input) {
if (input.value < 2) input.value = 2;
if (input.value >= 100) input.value = 99.99;
cadConvert();
}
I also took out the onkeyup="cadConvert() because you are calling that in cadCheck() and added this("this" being the input's value) to onchange="cadCheck().
new html <input id="cadc" type="text" onchange="cadCheck(this)">CAD</input>
Here is my code https://jsfiddle.net/so7s9efr/
Don't mean to be the "just use this" guy, but currency conversion is a common, solved problem and there are many good solutions out there.
A good one is money.js
Was working on a fiddle solution, but Paul Allen's works fine.

entry in input one by one should show added result in result field

when user select any option in radio buttons in group one and then enter any number in respective input field and then select the next any radio option and enter any value in input field then this time it should add the new result with old one and display it in result input field and now if he empty any input field then that should also minus from the total result and display it in result field.
i have so many groups like that but here i just put two of them to get the result.
here id the FIDDLE
here is the jquery code. i can work in jquery but not very good i used separate code for every group and i know there must be a way to get this whole functionality through generic code but again i am not good at jquery
jQuery("#txt_im").keyup(setValue);
jQuery('[name="rdbtn-im"]').change(setValue);
function setValue() {
var txt_value = jQuery("#txt_im").val();
var rad_val = jQuery('[name="rdbtn-im"]:checked').val();
if(!txt_value.length) {
jQuery('#final_res').val('');
return;
}
if (!rad_val.length) return;
var res = txt_value * rad_val;
var final = parseInt(res, 10);
var MBresult = final / 1024;
jQuery('#final_res').val(MBresult.toFixed(2));
}
var final2 = 0;
jQuery("#txt_fb").keyup(setValue2);
jQuery('[name="rdbtn-fb"]').change(setValue2);
function setValue2() {
var txt_value = jQuery("#txt_fb").val();
var rad_val = jQuery('[name="rdbtn-fb"]:checked').val();
if(!txt_value.length) {
jQuery('#final_res').val('');
return;
}
if (!rad_val.length) return;
var res2 = txt_value * rad_val;
final2 = parseInt(res2, 10) + final;
var MBresult = final2 / 1024;
jQuery('#final_res').val(MBresult.toFixed(2));
}
infact user is free to select any number of groups or also free to remove any number of group after selection.
i know there is error in fiddle when user select 2nd group after the select of first it removes the result which is wron and i tried to solve it but failed but i define the whole seen what i need to do. i will be very thankfull to you for this kind favour.
HTML:
<table>
<tr>
<td>
<input type="radio" name="rdbtn-im" id="rdbtn-im-day" value="25" class="rdbtn-style-social" />Daily
<input type="radio" name="rdbtn-im" id="rdbtn-im-week" value="175" class="rdbtn-style-social" />Weekly
<input type="text" name="txb3" id="txt_im" class="txt-email" style="width:100px;margin: 2px;" />
</td>
</tr>
<tr>
<td class="sec-td-rdbtns-social">
<input type="radio" name="rdbtn-fb" id="rdbtn-fb-day" value="3500" class="rdbtn-style-social" />Daily
<input type="radio" name="rdbtn-fb" id="rdbtn-fb-week" value="500" class="rdbtn-style-social" />Weekly
<input type="text" name="txb1" id="txt_fb" class="txt-email" style="width:100px;margin: 2px;" /> </td>
</tr>
</table>
<br>result
<input type="text" name="final_res" id="final_res" class="" style="width:100px;margin: 2px;" />
Jquery:
jQuery(".txt-email").keyup(setValue);
jQuery('.rdbtn-style-social').change(setValue);
function setValue() {
var total = 0;
$(".rdbtn-style-social:checked").each(function () {
var myInput = $(this).siblings(".txt-email").val();
if (myInput.length) {
total += myInput * $(this).val();
}
});
if (total) {
jQuery('#final_res').val((total / 1024).toFixed(2));
} else {
jQuery('#final_res').val('');
}
}
FIDDLE
If you are using chrome, then console is your best friend ( https://developers.google.com/chrome-developer-tools/docs/console )
For firefox you have firebug, opera has dragonfly (or something like that ?). Even IE has console now. There you can see all errors popping up.
Ok, so first of all let's clean up this a little bit by wrapping it all in closure (we can now safely use the $ instead of jQuery even if there is namespace conflict outside). Also, we will use single function for both cases, because they are so similar.
!function ($) {
$(".txt-email").keyup(setValue);
$('.rdbtn-style-social').change(function(e) { setValue(e, true) });
function setValue(e, radio) {
if('undefined' === typeof radio) radio = false;
var attr = radio ? 'name' : 'id';
var tmp = e.target[attr].split('-');
var media = tmp[tmp.length - 1];
var txt_value = $("#txt-"+media).val();
var rad_val = $('.rdbtn-style-social[name="rdbtn-'+media+'"]:checked').val();
if (!txt_value.length || !rad_val.length) {
$('#final_res').val('');
return false;
}
var res = (txt_value | 0) * rad_val;
var final = parseInt(res, 10);
var MBresult = final / 1024;
$('#final_res').val(MBresult.toFixed(2));
}
}(jQuery);
(variable | 0 is same as parseInt(variable, 10)).
So, long story short: when radio or text gets changed, the function is fired (if it's radio, additional argument is passed). We retrieve whether we want to work on im or fb, then do whatever you want. I changed id of inputs to replace _ with -'s (for split consistency)
Final jsfiddle: http://jsfiddle.net/Misiur/f6cxA/1/

Categories