I am trying to do more than one javascript math function , i put two inputs , the first makes the own calculate and the result of the first , be part of the second calculate .
For example:
HTML
Total:
<input type="text" id="1" value="" />
<p id="5"></p>
AMPI:
<input type="text" id="2" value="" />
<p id="4" ></p>
javascript
$("#1").keyup(function () {
var value = $(this).val();
var x=value*value;
$("#3").text(x);
}).keyup();
$("#2").keyup(function () {
var value = $(this).val();
var y=value/ (**here i want the output <p id="3"></p>**) ;
$("#4").text(y);
}).keyup();
Stating the obvious, you need to replace (**here i want the output <p id="3"></p>**) with $("#3").text();.
See, also, this short demo.
UPDATE:
In order to limit the number of fractional digits, you can use function toFixed. E.g.:
var x = 123.456789
$("#3").text(x.toFixed(3)); // <-- Displays: 123.457
Related
I have created a simple calculator that takes variable #1 and variable #2 and multiplies them to generate a result.
When I change variable #1 the result instantly changes. However, when I change variable #2 the result remains unchanged.
How do I reconfigure my code so that the result instantly changes when either variable is altered?
HTML:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h6>Variable #1</h6>
<input id="var1">
<h6>Variable #2</h6>
<input id="var2">
<h6>Result</h6>
<input readonly="readonly" id="result">
<script>
$(document).ready(function(){
var mt=$("#var1");
mt.keyup(function(){
var total=isNaN(parseInt(mt.val()* $("#var2").val())) ? 0 :(mt.val()* $("#result").val())
$("#result").val(total);
});
});
</script>
You have many things going wrong here,
you need to bind keyup event in var1 textbox and var2 textbox both
Also, your multiply formula is also wrong. Here is the desire code:
$(document).ready(function(){
var mt=$("#var1,#var2");
mt.keyup(function(){
debugger;
var total= 0;
if(!isNaN(parseInt($("#var1").val())* parseInt(parseInt($("#var2").val())))){
total= parseInt($("#var1").val())* parseInt(parseInt($("#var2").val()));
}
$("#result").val(total);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h6>Variable #1</h6>
<input id="var1">
<h6>Variable #2</h6>
<input id="var2">
<h6>Result</h6>
<input readonly="readonly" id="result">
Consider binding keyup events on both #var1 and #var2 inputs using the following jQuery syntax #var1, #var2 to achieve this desired behaviour, as shown:
$(document).ready(function(){
// Select and bind keyup event to both "var" input elements using
// this syntax
$('#var1, #var2')
.keyup(function(){
// Adjust your keyup handler to perform calculation when keyup
// occurs on either input field
var total= 0;
if(!isNaN(parseInt($("#var1").val())* parseInt($("#var2").val()))){
total = parseFloat($("#var1").val())* parseFloat($("#var2").val());
}
$("#result").val(total);
});
});
I just want to answer in vanilla Javascript for future reference of the problem..
I make var1,var2 class="input", then querySelect them both, then loop them, so that when you put any number to them, their value(product) will be produce in the id="result"
if you did not put any number to them, the default value is zero(0) for both of them, so let say, you only put 10 to var1, then the output will only be 10, and if you put non numeric character, then the output is NaN.
let input = document.querySelectorAll(".input");
let var1 = document.querySelector("#var1");
let var2 = document.querySelector("#var2");
let output = document.querySelector("#result");
function result(var1=0,var2=0) {
output.value = Number(var1)*Number(var2);
}
for(let i=0;i<input.length;i++)
{
input[i].addEventListener(`keyup`,()=>result(var1.value,var2.value))
}
<h6>Variable #1</h6>
<input id="var1" class="input">
<h6>Variable #2</h6>
<input id="var2" class="input">
<h6>Result</h6>
<input readonly="readonly" id="result">
By the way you can also make the code much shorter by instead of putting the id var1,var2 value, you can instead just put the input class[0], and [1] it's the same..
so it can also be done this way.
let input = document.querySelectorAll(".input");
let output = document.querySelector("#result");
function result(var1=0,var2=0) {
output.value = Number(var1)*Number(var2);
}
for(let i=0;i<input.length;i++)
{
input[i].addEventListener(`keyup`,()=>result(input[0].value,input[1].value))
}
<h6>Variable #1</h6>
<input id="var1" class="input">
<h6>Variable #2</h6>
<input id="var2" class="input">
<h6>Result</h6>
<input readonly="readonly" id="result">
By the way if you want to follow the same logic by using ternary operator,
let's follow his example, by using ternary operator,
change the result function to this.
function result(var1=0,var2=0) {
(var1*var2 ===0)? output.value=0: output.value=Number(var1) * Number(var2);
}
I have a script. This script has to do some calculations. For the reason that now the user has to edit the script variables in the file I want to write a form that updates the variables always when the form is updated. There are around 10 variables that needs to be updated always when one variable in the form is updated.
For example:
In the HTML form are 10 fields like this one (the onchange="formChanged()" is from the try):
<input type="number" name="pL" step="0.001" value="250000" onchange="formChanged()"/><br>
So I want to edit this variable in JavaScript:
var pL=250000;
I tried this:
function formChanged() {
var x = document.getElementsByName("x")[0].value
var m0 = document.getElementsByName("pL")[0].value
var V = document.getElementsByName("V")[0].value
}
But this doesn't work...
Do you have any suggestions, what I'm doing wrong?
See https://www.w3schools.com/jsref/met_doc_getelementsbyname.asp
It should be getElementsByName.
<!DOCTYPE html>
<html>
<body>
<input type="number" name="pL" step="0.001" value="250000" onchange="formChanged()"/><br>
<input type="number" name="x" step="0.001" value="250000" onchange="formChanged()"/><br>
<input type="number" name="V" step="0.001" value="250000" onchange="formChanged()"/><br>
<p id="demo"></p>
<script>function formChanged() {
var x = document.getElementsByName("x")[0].value
var m0 = document.getElementsByName("pL")[0].value
var V = document.getElementsByName("V")[0].value
document.getElementById("demo").innerHTML = x + ' ' + m0 + ' ' + V;
}
</script>
</body>
</html>
This works. Add a snippet with the whole code, please.
if you want to change the value of the variable through javascript, assign the value to it's value property.
so instead of
pL=250000;
write, in your formChanged function
document.getElementsByName("pL")[0].value=250000;
also it is not clear from your question on the calculation you want to do on the
if say you want to add the values x and V to be the new pL
then write
var x = document.getElementsByName("x")[0].value
var m0 = document.getElementsByName("pL")[0].value
var V = document.getElementsByName("V")[0].value
document.getElementsByName("pL")[0].value=Number(x)+Number(V)
In HTML5, the "name" attribute is deprecated and has been replaced by the "id" attribute for many elements. I've tried the following and it worked for me.
<input type="number" id="pL" step="0.001" value="250000" onchange="formChanged()"/>
<script>
function formChanged() {
var m0 = document.getElementById("pL").value;
alert("The current value is " + m0);
}
</script>
Let me know if this works for you too. Also make sure you put semi-colons after your statements in the formChanged() function.
I'm working on a dynamic calculation program to practice jquery, but so far it's not going well, I can store the values in a variable, of course (see code here).
<form>
Tafeltje van:
<input type="number" name="tafel" id="tafel" />
Aantal:
<input type="number" name="aantal" id="aantal" />
</form>
<div id="output"></div>
and the JS:
var tafel = $('#tafel').val();
var aantal = $('#aantal').val();
How would one be able to print out these values in output while the user is typing in the text fields?
You can bind your code with keyup or input event of the inputs. Then, once you have got the values, you can use either text() or html() to display the values in #output div in whatever format you want.
// $("input").on("keyup", function(){
$("input").on("input", function(){
var tafel = $('#tafel').val();
var aantal = $('#aantal').val();
$("#output").text("tafel: " + tafel + " aantal: "+aantal);
});//keyup
I have a bunch of div's that have the same functionality and I'm trying to write a function for them.
Basically they have a predetermined value and a user input value and those need to be multiplied.
I've looked through a bunch of other questions and this is the closest one I could find. Almost exactly, but none of those answers work.
Any help would be great. Thanks in advance!
<div>
<label>enter value for multiple here</label>
<input type="text" class="multiple" factor="foo1"/>
<button type="button" class="multiplyBtn">Click here to multiply these numbers</button>
<label>enter value for multiple here</label>
<input type="text" class="multiple" factor="foo2"/>
<button type="button" class="multiplyBtn">Click here to multiply these numbers</button>
</div>
Here's the JS:
$('.mulitplyBtn').click(function() {
var factor = $(this).closest('attr.factor').val();
var multiple = $(this)closest('.multiple').val();
answer = (factor * multiple);
};
This would work:
$('.multiplyBtn').click(function() { // you had multiplyBtn spelled wrong here
var cur = $('.multiplyBtn').index($(this)); // get index of clicked btn
var factor = $('.multiple').eq(cur).data('factor'); // get factor from matching input
var multiple = $('.multiple').eq(cur).val(); // get value from matching input
answer = (Number(factor) * Number(multiple)); // make sure both are numbers then multiply
alert(answer);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<label>enter value for multiple here</label>
<input type="text" class="multiple" data-factor="4" />
<button type="button" class="multiplyBtn">Click here to multiply these numbers</button>
<br>
<label>enter value for multiple here</label>
<input type="text" class="multiple" data-factor="7" />
<button type="button" class="multiplyBtn">Click here to multiply these numbers</button>
</div>
In the first line you used " and ' try using the same quotes (I mean using ".multiplyBtn" or '.multiplyBtn' )
Second time, 3rd line you didn't use any quote when calling .multiple. So turn it in that format : var multiple = $(this)closest('.multiple').val()
let me know the result
You have at least two typos and are using the wrong jQuery function.
Typos:
$('.mulitplyBtn') should be $('.mulitplyBtn')
$(this)closest should be $(this).closest
Wrong function:
closest() searches the parents, and the only parent here is the DIV with no class. What you probably want is to use parent() to go up to the DIV, then find() to search the parent's children for a specific element:
$(this).parent().find('.multiple').val()
attr.factor does not work like this.
try it like this:
$('.multiplyBtn').click(function() {
var container = $(this).prev('.multiple'); //don't forget the "dot"
var multiple = container.val();
var factor = container.attr('factor'); //since it is the same container.
var answer = (factor * multiple); //what exactly are you tryin to multiply?
};
http://jsfiddle.net/beY6d/
I want to make a simple HTML+JS page that basically gives the user 4 text fields to write the name of some product and an extra field that displays the remaining credit in the 5th text field.
<input type="text" value="0" class="product" id="shirtItems"/><br>
<input type="text" value="0" class="product" id="pantsItems"/><br>
<input type="text" value="0" class="product" id="hatItems"/><br>
<input type="text" value="0" class="product" id="accesoryItems"/><br>
<input type="text" value="100" id="credit" disabled/>
var shirt= document.getElementById("shirtItems");
var pants= document.getElementById("pantsItems");
var hat= document.getElementById("hatItems");
var accesory= document.getElementById("accesoryItems");
var remainingDosh = document.getElementById("credit");
remainingDosh.value = 100;
There must be a .onblur (or .onfocus) event to make the "credit" field display 100 minus the sum of every other item.
Also, the price of the item must change depending on the color/type of item. Something like:
shirt.onblur = function(){
if (shirt.value == "Blue") {remainingDosh.value = remainingDosh-25}
if (shirt.value == "Red") {remainingDosh.value = remainingDosh-20;}
};
If you do typeof remainingDosh.value, you'll see that it logs string. This means you'll have to convert the string to a number if you don't want to risk having NaN show up on your page.
Convert it with parseInt() like so:
var remainingDosh.value = parseInt(remainingDosh,10)-25;
The second parameter, 10 is the radix, which in this case is decimal (though it defaults to decimal if left out I believe).
And the issue in question, as pointed out, is you're trying to do math on the element remainingDosh instead of using it's value.
Oh, and protip: instead of shirt.value, you can use this.value since the event comes from said element.
you're using remainingDosh instead of remainingDosh.value when you do your subtraction.