I'm trying to animate an output which is calculated based on a single input value * 4.5. The calculation itself is working but I cannot figure out how to animate the value, what I'm trying to do is have the output count up to the calculated value quite quickly. I've found https://codepen.io/shivasurya/pen/FatiB which has the count animation I'd like to implement, but can't figure out how to implement it to my input and output fields, so far I have:
<form id="ewcalc" oninput="updateOutput()">
<input name="income" type="number" value="0" />
<output for="income" name="loan">0</output>
</form>
<script type="text/javascript">
function updateOutput() {
var form = document.getElementById("ewcalc");
form.elements["loan"].value=eval(parseInt(form.elements["income"].value) * 4.5);
}
</script>
Any suggestions how I can implement the animation? I've tried several things, none of which are working, and getting errors if I try using onsubmit.
You'll probably want to use requestAnimationFrame like this:
function updateOutput() {
var income = $("#income").val() * 4.5;
var output = Number($("#loan").text());
if (income !== output) {
if (income > output)
output += 0.5;
else if (income < output)
output -= 0.5;
$("#loan").text(output);
requestAnimationFrame(updateOutput);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form id="ewcalc" oninput="updateOutput()">
<input id="income" type="number" value="0" />
<output for="income" id="loan">0</output>
</form>
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.
Is there a way to group together multiple html5 slider fields. Originally I tried doing this will type=number fields but I didn't like the way it looked.
So what I what I have is 7 fields that I want to use sliders with individual min values of 0 and max values of 100 - however - the trick is that I need a way to add them all up to make sure in total they equal 100. None of the fields individually are required. Does that make sense?
Here is the function I tried but its not working at all:
<script>
function percentageTest() {
// Get the value of the input fields
a = document.getElementById("cuts").value;
b = document.getElementById("burns").value;
c = document.getElementById("infection").value;
d = document.getElementById("dermatitis").value;
e = document.getElementById("puncture").value;
f = document.getElementById("sprain").value;
g = document.getElementById("impact").value;
var x = (a + b + c + d + e + f + g);
// grouping together and doing the math
if (x != 100) {
text = "The total percentage must equal 100%";
}
document.getElementById("rec_injuries").innerHTML = text;
}
</script>
You can do something like this (just make it pretty and adapt it to your needs):
HTML
<form>
<formgroup class="ranges">
<input type="range" min="0" max="100">
<input type="range" min="0" max="100">
<input type="range" min="0" max="100">
<input type="range" min="0" max="100">
</formgroup>
</form>
JavaScript
var ranges = Array.from(document.querySelector('.ranges').children);
var total = ranges.reduce(function(acc, curr) {
return acc + Number(curr.value)
}, 0)
// Now you can check total
#Dave Gomez answers is way more elegant, please use it instead. But if you are wondering why it wasn't working :
Your document.getElementById("cuts").value; return strings. You need to convert them to int before adding them. This can be done like this :
a = +document.getElementById("cuts").value;
b = +document.getElementById("burns").value;
... etc
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;
I am a beginner and I have the following problem/code for the main body:
<body>
<form action="#">
<input type="text" id="start" />
=
<input type="text" id="finish" />
</form>
<script>
$(function() {
var cVal = $("#start").val();
var fVal = $("#finish").val();
});
</script>
</body>
With two text boxes, I would like the value entered in the celsius text box to be converted into fahrenheit in the other text box. I have tried to use the
keyup()
function but failed to produce the results I want.
typing 15 into the celsius box should result in 59 in fahrenheit. I understand that .val() does not take any arguments, so where would I do the computation for converting the numbers? And how can I incorporate keyup?
Any help is appreciated!
The val function does take arguments, you can pass it the new value and it will update textbox contents. Click the link on val, it will take you to the jQuery documentation, where all possible calls are explained. Or see the example below.
function fahrenheitToCelsius(fahrenheit) {
var val = 0;
// perform calculation
return val;
}
function celsiusToFarenheit(celsius) {
var val = 0;
// perform calculation
return val;
}
$(function() {
$("#start").on('keyup', function() {
$("#finish").val(celsiusToFarenheit($(this).val()));
});
$("#finish").on('keyup', function() {
$("#start").val(fahrenheitToCelsius($(this).val()));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="#">
<input type="text" id="start" /> Celsius
=
<input type="text" id="finish" /> Fahrenheit
</form>
This is such a simple thing to do, jQuery is not needed at all, and because you haven't tagged jQuery here comes a plain javascript solution.
What you need to do is the add a keyup trigger on each of the input elements.
To grab our input fields we use document.getElementById(id), we use this because you've added the id attribute to your fields (it's faster than the latter method I'm mentioning). We could've used document.querySelector(selector) to get our input fields to. If you had used name="celsius" on the celsius field, we could've used document.querySelector('input[name="celsius"]') to grab that element.
What we need to do next is to an a keyup trigger to both our input fields. This is done with element.onkeyup = function() {}, in each of those functions we calculate the value for the other field.
var celsius = document.getElementById('start'),
fahrenheit = document.getElementById('finish');
celsius.onkeyup = function() {
fahrenheit.value = this.value * 9/5 + 32;
}
fahrenheit.onkeyup = function() {
celsius.value = (this.value - 32) * 5/9;
}
<form action="#">
<input type="text" id="start" /> Celsius
=
<input type="text" id="finish" /> Fahrenheit
</form>
The jQuery .val() function is an overload function which means it takes 0 up to 1 argument and it's effect varies on the number of arguments passed.
As you can see in my example calling celsiusInput.val() just returns the current value of the field. However if you use it like this farenheitOutput.val(farenheit) the current value of the input is overwritten by the variable passed.
const updateFarenheit = () => {
// find the input and output in the dom by their id
const celsiusInput = $("#start");
const farenheitOutput = $("#finish");
// get the input value
const celsius = celsiusInput.val();
const farenheit = celsius * 9 / 5 + 32;
// update the farenheit output
farenheitOutput.val(farenheit);
}
// this function runs when all js is loaded aka. "document ready"
$(document).ready(function() {
// get input field by id
const celsiusInput = $("#start");
// we pass the updateFarenheit function we defined before as the function which should run
// as soon as the keyup event occures on our celsiusInput field
celsiusInput.keyup(updateFarenheit);
});
<html lang="">
<head>
<meta charset="utf-8">
<title>Celsius to Farenheit</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<form action="#">
<input type="text" id="start" /> =
<input type="text" id="finish" />
</form>
</body>
</html>
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.