Automatic percentage calculator - javascript

I am working on a code to calculate percentage but I need it to calculate the percentage automatically without the submit button, that is I want it to output the calculated percentage without the need of the user hitting the submit button.
Here is my code
Input: <input type="text" id="input"/><br />
Percent: <input type="text" id="percent" value="50"/>%<br />
Output: <input type="text" id="output"/>
function calc() {
var i = document.getElementById("input").value;
var p = document.getElementById("percent").value;
var o = (i/100) * p;
document.getElementById("output").value = o;
}

On each of the two inputs, add onchange="calc();" (updates when user tabs to the next field) or onkeyup="calc();" (updates whenever user types something).

Related

It seems onChange="myFunction()" is only calling my function once?

I have the following HTML that is within a form, to accept 2 numbers from two separate inputs
<input type="number" id="amount" name="amount" value="0" onchange="ltv()">
<input type="number" id="property_value" name="property_value" value="0" onchange="ltv()">
<p id="ltv"></p>
Then some JavaScript
function ltv() {
var amount = document.getElementById("amount").textContent;
var property_value = document.getElementById("property_value").textContent;
document.getElementById("ltv").innerHTML = Math.round(amount/property_value*100);
};
However after entering a number into the "amount" input the ltv element is updated with NaN which is to be expected at this stage as only the first variable in the math operation is set, however upon entering the second number and tabbing away from the input field the ltv is not updated again.
Seems like textContent isn't returning anything. Try to use .value
function ltv() {
var amount = document.getElementById("amount").value;
var property_value = document.getElementById("property_value").value;
document.getElementById("ltv").innerHTML = Math.round(amount/property_value*100);
};

Set max value based on another input

I need to set a max value of an input based on the value of another input.
I will have two inputs, input x and input y, a user inputs a value in each but the value for y can be no more than 80% of the value of x, so I want a max value on input y so you can't go over 80% of input x.
so if someone puts 100 in input x and tries to put 90 in input y, input y would change to be 80 because that would be the max.
I intend to use javascript and HTML to achieve this.
I suggest monitoring the input using the onchange event of both fields and limiting the value using Math.min(...)
Here is a snippet:
var elX = document.getElementById("X");
var elY = document.getElementById("Y");
function limit() {
elY.value=Math.min(Math.round(elX.value*.8),elY.value);
}
elX.onchange=limit;
elY.onchange=limit;
<input type="number" id="X" value="0"><br>
<input type="number" id="Y" value="0">
Here is a simple solution using JQuery and 2 simple input fields. It pretty much does what you want -> JSFiddle
Related HTML:
<input type="number"id="x">
<input type="number" id="y">
Related JS:
(function(){
$("#y").on("change", function(e){
var x = $("#x").val()
if($(this).val() > (x*80)/100){
$(this).val(((x*80)/100));
alert("field Y cannot excede 80% of field X")
}
})
}())
If I understand right:
The input is like something this:
<input type="number" id="Y" max="numberHere">
You can do it like this:
var temp = document.getElementById("Y");
var maxValue = document.getElementById("X").value * 0.8;
temp.setAttribute("max",maxValue); // set a new value;

Creating a form entry calculator with jQuery

I am trying to build a calculator using form entries as the figures to be calculated and returned to corresponding form fields in another field set. I am fairly new to jQuery and I am following the advice of a book but I must be honest, I do need to rush this a bit and I'm having some problems.
Here is the jfiddle if you need to visualise it: http://jsfiddle.net/u3xx4ubv/14/
EDIT: Not sure on the appropriate form action for this, which may be causing some problems.
HTML:
<form action="" method="get" id="ATSCalc">
<fieldset>
<legend>Return on Investment Calculator</legend>
<label for="aptsBooked" class="label">Avg. Appointments Booked</label>
<input name="aptsBooked" type="text" id="aptsBooked">
<br />
<label for="aptsAttended" class="label">Avg. Appointments Attended</label>
<input name="aptsAttended" type="text" id="aptsAttended">
<br />
<label for="reqMeetings" class="label">Meetings per deal</label>
<input name="reqMeetings" type="text" id="reqMeetings">
<br />
<label for="orderVal" class="label">Avg. order value</label>
<input name="reqMeetings" type="text" id="reqMeetings">
<br />
<input type="submit" value="Submit" />
</fieldset>
<br />
<fieldset>
<legend>Results</legend>
<label for="convRate" class="label">Appointment conversion rate</label>
<input name="convRate" type="text" id="convRate">
<br />
<label for="meetingsPerDeal" class="label">No. of meetings per deal</label>
<input name="meetingsPerDeal" type="text" id="meetingsPerDeal">
<br />
<label for="meetingVal" class="label">Value of each meeting</label>
<input name="meetingVal" type="text" id="meetingVal">
<br />
</fieldset>
</form>
JavaScript:
$(document).ready(function(){
$('#ATSCalc').submit(function(){
var aptsBooked = $('#aptsBooked').val();
var aptsAttended = $('#aptsAttended').val();
var reqMeetings = $('#reqMeetings').val();
var orderVal = $('#orderVal').val();
//Collects values of form input
var aptsConvRate = aptsAttended / aptsBooked * 100;
$('#convRate').val(aptsCovRate); //Outputs meeting conversion rate to form field.
var meetingsPerDeal = aptsBooked / reqMeetings;
$('#meetingsPerDeal').val(meetingsPerDeal); //Outputs meeting per deal value to form field.
var meetingVal = orderVal / meetingsPerDeal;
$('#meetingVal').val(meetingVal); //Outputs value of each meeting to form field.
//Variables for calculation of Return on Investment figures
}}; // end submit()
}}; // end ready ()
I am trying to run the second group of variables and return the outputs in the fields seen in the second fieldset. I imagine it is just syntax errors or misplaced code but I am really struggling to fix it. Any help would be much appreciated.
Fiddle example
You missed
}}; instead of }); as your closing brackets
variable name aptsCovRate instead of aptsConvRate ( missing n )
$(document).ready(function () {
$('#ATSCalc').submit(function (e) {
e.preventDefault();
var aptsBooked = parseInt($('#aptsBooked').val(), 10);
var aptsAttended = parseInt($('#aptsAttended').val(), 10);
var reqMeetings = parseInt($('#reqMeetings').val(), 10);
var orderVal = parseFloat($('#orderVal').val());
//Collects values of form input
var aptsConvRate = aptsAttended / aptsBooked * 100;
$('#convRate').val(aptsConvRate); //Outputs meeting conversion rate to form field.
/* ^^^^ Conv !! not Cov */
var meetingsPerDeal = aptsBooked / reqMeetings;
$('#meetingsPerDeal').val(meetingsPerDeal); //Outputs meeting per deal value to form field.
var meetingVal = orderVal / meetingsPerDeal;
$('#meetingVal').val(meetingVal); //Outputs value of each meeting to form field.
//Variables for calculation of Return on Investment figures
}); // end submit()
}); // end ready ()
Also, it would be good to use parseInt() (value to integer Docs) with radix parameter and parseFloat() (value to floating-point number Docs) methods while getting your Number values from your inputs.
To round your results take a look at the toFixed() method.
There are a few things wrong with your javascript/HTML, and a few things you missed.
$('#convRate').val(aptsCovRate); should be $('#convRate').val(aptsCo**n**vRate);
The end submit and end ready should be }); not }};
You do not have a HTML input with orderVal as an ID. It needs to be changed.
Finally, what you missed - your form will submit and refresh and you'll lose the calculated values. You can fix this by using e.stopPropagation(); and e.preventDefault();
Updated fiddle should be working for you: http://jsfiddle.net/u3xx4ubv/17/

javascript calculation field comparison algorithm

Good day,
I have 3 text fields for input.
TotalWeight
CustomUnitWeight
CustomsNumberOfUnit
There should be a validation to make sure TotalCustomWeight matches TotalWeight (neither higher nor lower).
I started playing around trying to construct a function for validating this no luck and looking for assistance
Scenario :
User input total weight of pkg at 30, then put number of custom unit at 2 and the weight at 10. On click the function calculate 2 * 10 = 20 and look at the total weight 30 and compare the total custom weight. In this case 20 does not equal to 30 therfore throw error message.
HTML
<input type="text" name="TotalWeight" id="TotalWeight" />
<input type="text" name="customsNumberOfUnitsUSA" id="CustomsNumberOfUnits" />
<input type="text" name="CustomsUnitWeight" id="CustomsUnitWeight" onChange="ChkWeight();" />
JAVASCRIPT
$(function(ChkWeight){
$('#CustomsUnitWeight').click(function() {
var TotalWeight = document.getElementById('TotalWeight');
var CustomUnitWeight = document.getElementById('CustomsUnitWeight');
var CustomsNumberOfUnit = document.getElementById('CustomsNumberOfUnits');
var TotalCustomWeight = CustomUnitWeight * CustomsNumberOfUnit;
if (TotalWeight != TotalCustomWeight) {
error message "pkg weight does not match total custom weight"
}
});
});
Well everything else is fine in your code just needs to put .value to get value from your input fields and converting string (simple text) to Float type and then calculate and show alert like
<body>
<input type="text" name="TotalWeight" id="TotalWeight" />
<input type="text" name="customsNumberOfUnits" id="CustomsNumberOfUnits"/>
<input type="text" name="CustomsUnitWeight" id="CustomsUnitWeight" onblur="CheckWeight()" />
//I have changed the event as onblur and calling CheckWeight() function defined in javascript below.
</body>
<script type="text/javascrit">
function CheckWeight()
{
var TotalWeight = document.getElementById('TotalWeight').value;
var CustomUnitWeight = document.getElementById('CustomsUnitWeight').value;
var CustomsNumberOfUnit = document.getElementById('CustomsNumberOfUnits').value;
//parsing text value to Float type for multipication
var TotalCustomWeight = parseFloat(CustomUnitWeight) * parseFloat(CustomsNumberOfUnit);
if (TotalWeight != TotalCustomWeight)
{
alert("pkg weight does not match total custom weight");
}
}
</script
and Off course you must need to validate for value to be number before calculation. This works perfect.

Calculate one variable based on changing input

I have the following function:
function updateInput(ish){
document.getElementById("BetAmount").value = ish;
}
I have the following HTML inputs:
<input class="defaultText" type="number" name="BetAmount" id="BetAmount" onchange="updateInput(this.value)">
<input type="number" name="PotentialGain" id="PotentialGain" />
When users enter in a bet amount number(BetAmount), I would like to instantly show a calculated PotentialGain, which, for example, can be found by multiplying a constant by the specified bet amount entered in by the user.
I'm not very familiar with JavaScript, so any help is greatly appreciated!
Your code is almost correct - you are showing the result in the BetAmount field so no change is visible.
Change your code to:
document.getElementById("PotentialGain").value = ish;
Here's a working demo. I changed the event to onkeyup as onchange only happens on blur - i.e. when a field loses focus.
Here is the final JQuery function that I used.
function changeBet(bet) {
var moneyline = <?php echo json_encode($win) ?>;
var gain = moneyline * bet;
document.getElementById("PotentialGain").value = gain;
}
Along with these inputs:
<input type="text" name="BetAmount[]" id="BetAmount" onkeyup="changeBet(this.value);" >
<input type="number" name="PotentialGain" id="PotentialGain" />

Categories