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/
Related
I’m looking for a way to automate a form.
Here are the details:
Extract a certain number (displayed in its html)
Do some calculations on the extracted number (percentage of that number)
Then automatically fill the remaining input fields with the result instead of typing it out.
This is a common occurrence in forms. The solution depends on what framework / libraries you're using. Assuming you're using none, here is how you might go about it:
https://jsfiddle.net/f52h1smj/1/
rough HTML:
<form>
<label for="number">Number: </label>
<input id="number" type="number" />
<br /> <br />
<label for="calculatedNumber">Calculated Number (50%): </label>
<input id="calculatedNumber" type="number" disabled="true" />
</form>
JS:
(() => {
//get the form element nodes
const $number = document.getElementById("number");
const $calculatedNumber = document.getElementById("calculatedNumber");
//add an event listen to the value you're going to use to pre calculate the other fields
$number.addEventListener("keyup", (e) => {
//it's value is available like so
const value = e.target.value;
//do some validation so that you're calculations don't throw exceptions
if (Number(value) !== 0 && !Number.isNaN(value)) {
//set the value of the other inputs to whatever you like by setting the 'value' property of the node.
$calculatedNumber.value = value / 2;
} else {
$calculatedNumber.value = null;
}
});
})();
These things become a lot simpler in frameworks like React and Angular.
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).
I am attempting to create an equation using people's pay rates and some other information from a from. However, I can't even get variables to set based on information from the form. The form includes 1 set of radio buttons and 2 text input forms.
<form id="userInfo" action="" method="post">
<p>Pay Frequency: <select name="payFreqS">
<option>Hourly</option>
<option>Weekly</option>
<option>Bi-Weekly</option>
<option>Monthly</option>
</select></p>
<p>Pay Rate:<input type="text" name="payRateS" value="0000.00">
</p>
<p>Cost of Item:<input type="text" name="costS" value="000.00">
</p>
</form>
<p><input name="submit" type="submit" class="btn" value="Submit" onclick="shouldIBuy()"/></p>
Javascript:
function shouldIBuy()
{
// attempt to find error with console statements
console.log("How far can we get?");
// setting variables for my function
var payRate = document.getElementByIds("payRateS").value;
var cost = document.getElementById("costS").value;
// pay frequency variable
var payFreq = document.forms[0].payFreqS;
var i;
for (i=0;i<payFreq.length;i++)
{
if (payFreq[i].checked)
{
payFreqVal = i;
}
}
//more console.log statements to troubleshoot
console.log(cost);
console.log(payRate);
console.log(payFreq);
// setting what I hoped were strings to integers.
var payRateInt = parseInt(payRate);
var costInt = parseInt(cost);
There should be errors in your console because you are using the non-existent getElementByIds.
I went back and broke it down to the very basic elements to figure out was going on. I was not referencing the right things. You were right. Thanks.
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.
I'm Working with form validation and fields for the first time without inline event handling. I can't find an example of how to pass a integer value, do a operation on it and pass to another field. This is what I'm up against:
FORM LOOKS LIKE THIS:
ITEM CONTAINER QUANTITY PRICE EXTENDEDCOST
Small Beer Bottle,Can ?? #3.99/ea ??
HTML BITS
<form action="#" method="get" name="orderForm" id="orderForm">
<table id="products">
<input name="qtySmall" id="qtySmall" type="text" size="4" maxlength="6" value="" />
<input name="extSmall" id="extSmall" type="text" size="10" maxlength="60" value="" />
Javascript
window.onload = initForms;
function initForms()
{
document.getElementById("qtySmall").onfocus = detect;
document.getElementById("qtySmall").onchange = going_away;
document.getElementById("extSmall").value = passmyvalue; //not sure about this one yet
}
function detect()
{
alert("works")
}
function going_away()
{
pass_variable = document.getElementById("qtySmall").value;
}
function passmyvalue()
{
// I have no idea how to pass my qty small multiply it and pass it to the next field box 4 beers * 3.99 = 15.96 in extsmall
}
Thanks for the Help
Not sure if I am understanding your problem here. Can't you just change your going_away function to do the following?
function going_away()
{
pass_variable = document.getElementById("qtySmall").value;
document.getElementById("extSmall").value = parseInt(pass_variable) * cost;
}