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);
}
Related
I'm trying to use a input number type to update how many times a particular amount of content is added to the page. In the example I'm doing it with a p tag but in my main model I'm using it on a larger scale with multiple divs. However, I can't seem to be able to get this to work. If someone can see where I'm going wrong that would be very helpful.
function updatePage() {
var i = document.getElementById("numerInput").value;
document.getElementById("content").innerHTML =
while (i > 1) {
"<p>Content<p/><br>";
i--;
};
}
<input type="number" value="1" id="numberInput">
<br>
<input type="button" value="Update" onclick="updatePage()">
<div id="content">
<p>Content
<p>
<br>
</div>
First, you have quite a few problems that need addressing:
You are setting the .innerHTML to a while loop, which is invalid because a loop doesn't have a return value. And, inside your loop, you just have a string of HTML. It isn't being returned or assigned to anything, so nothing will happen with it.
You've also mis-spelled the id of your input:
document.getElementById("numerInput")
Also, don't use inline HTML event attributes (i.e. onclick) as there are many reasons not to use this 20+ year old antiquated technique that just will not die. Separate all your JavaScript work from your HTML.
Lastly, your HTML is invalid:
"<p>Content<p/><br>"
Should be:
"<p>Content</p>"
Notice that in addition to fixing the syntax for the closing p, the <br> has been removed. Don't use <br> simply to add spacing to a document - do that with CSS. <br> should be used only to insert a line feed into some content because that content should be broken up, but not into new sections.
Now, to solve your overall issue, what you should do is set the .innerHTML to the return value from a function or, more simply just the end result of what the loop creates as I'm showing below.
// Get DOM references just once in JavaScript
let input = document.getElementById("numberInput");
let btn = document.querySelector("input[type='button']");
// Set up event handlers in JavaScript, not HTML with standards-based code:
btn.addEventListener("click", updatePage);
function updatePage() {
var output = ""; // Will hold result
// Instead of a while loop, just a for loop that counts to the value entered into the input
for (var i = 0; i < input.value; i++) {
// Don't modify the DOM more than necessary (especially in a loop) for performance reasons
// Just build up a string with the desired output
output += "<p>Content</p>"; // Concatenate more data
};
// After the string has been built, update the DOM
document.getElementById("content").innerHTML = output;
}
<input type="number" value="1" id="numberInput">
<br>
<input type="button" value="Update">
<div id="content">
<p>Content</p>
</div>
And, if you truly do want the same string repeated the number of times that is entered into the input, then this can be a lot simpler with string.repeat().
// Get DOM references just once in JavaScript
let input = document.getElementById("numberInput");
let btn = document.querySelector("input[type='button']");
// Set up event handlers in JavaScript, not HTML with standards-based code:
btn.addEventListener("click", updatePage);
function updatePage() {
// Just use string.repeat()
document.getElementById("content").innerHTML = "<p>Content</p>".repeat(input.value);
}
<input type="number" value="1" id="numberInput">
<br>
<input type="button" value="Update">
<div id="content">
<p>Content</p>
</div>
As #ScottMarcus pointed out you had the following issues:
While Loops do not need a ; at the end of while(args) {}
Your .innerHTML code was in the wrong place
You had a typo in getElementById("numerInput") which I changed to getElementById("numberInput")
Code
function updatePage() {
// Get input value
var numberInput = document.getElementById("numberInput").value;
// Will be used to store all <p> contents
var template = "";
while (numberInput > 0) {
// Add all contents into template
template += "<p>Content<p/><br>";
numberInput--;
}
// Append upon clicking
document.getElementById("content").innerHTML = template;
}
<input type="number" value="1" id="numberInput">
<br>
<input type="button" value="Update" onclick="updatePage()">
<div id="content">
</div>
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 very simple form in HTML:
<form>
Number: <input id="form" type="text" name="Number"/>
</form>
Then I have this JavaScript:
var n = document.getElementById("form").value;
//calculations with n
//later, it outputs another variable (steps) that comes from that value of n
I want it to work out so that whenever the user types anything into the textbox, it does all of the JavaScript code and outputs the steps without having any submit button or anything like that. So if the user is going to type 123, for example, when they type 1, it will output steps when calculated for 1, then when they type the 2, it will output steps when calculated for 12, then when the type the 3, it will output steps when calculated for 123.
Use onInput event:
<input id="form" type="text" onInput="yourFunction();" />
JavaScript:
function yourFunction() {
var n = document.getElementById("form").value;
}
W3Schools documentation
Example:
function yourFunction() {
var n = document.getElementById("form").value;
document.getElementById("output").innerHTML = n;
}
Input: <input id="form" type="text" name="Number" onInput="yourFunction();" />
<div id="output"></div>
Register an onkeypress event handler on the input element and let that handler do the calculation. Btw you don't need the form container.
You need to trap the input event, and run your code in response
;(function(){
"use strict";
// make sure the DOM is available
document.addEventListener('DOMContentLoaded',function(){
// function that does the work
var calculateResult = function(event){
o.value = n.valueAsNumber.toString(2);
};
// select the DOM elements
var n = document.getElementById('n');
var o = document.getElementById('o');
// attach your function to the input event
n.addEventListener('input',calculateResult);
});
})();
<form id="f">
Number: <input id="n" type="number" name="n"/>
</form>
Number As Binary:
<output form="f" for="n" id="o"></output>
I want to pass the value of a input field in two spots. But my code only will pass it once. Is there a way to rewrite this to have it show up again down the code?
//HTML:
<input type="text" name="amount" onchange="passValue(this, 'preview_amount')"/>
//Outputs first value
<span id="preview_amount"></span>
//Outputs Nothing
<span id="preview_amount"></span>
//Javascript:
function passValue(e, target){
document.getElementById(target).innerHTML = e.value;
}
Your ids must be unique. Try this... It might work.
//HTML:
<input type="text" name="amount" onchange="passValue(this, 'preview_amount1', 'preview_amount2');"/>
//Outputs first value
<span id="preview_amount1"></span>
//Outputs Nothing
<span id="preview_amount2"></span>
//Javascript:
function passValue(e){
for(var i = 1; i < arguments.length; ++i){
if (document.getElementById(arguments[i]))
document.getElementById(arguments[i]).innerHTML = e.value;
}
}
With this you can pass any number of ids to passValue function without having to change it.
You cannot have duplicate element id's within a DOM document. ids MUST be unique.
Using jquery, and unique IDs, your problem becomes simple:
<input ... onChange="passValue(this, '#preview_amount1, #preview_amount2');" />
<span id="preview_amount1"></span>
<span id="preview_amount2"></span>
function passValue(e, targets) {
$(targets).innerHTML = e.value;
}
note the different IDs for the two spans, and how those IDs are passed withing the onChange handler.
Also try this one.
<input type="text" id="amount">
<div class="preview_amount"></div>
<div class="preview_amount"></div>
JQUERY
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script type = "text/javascript">
$(document).ready(function() {
$('#id').keypress(function() {
$('.preview_amount').html($(this).val());
});
});
</script>
You can set class name for all the spans you want to update onchange and then set innerHTML according to this class so you won't have to pass different id's to the function.
Fiddle
<input type="text" name="amount" onchange="passValue(this.value)"/>
<span class="set_values_here" id="preview_amount_1"></span>
<span class="set_values_here" id="preview_amount_2"></span>
<script>
function passValue(new_value) {
var els = document.getElementsByClassName("set_values_here");
for(var i=0; i<els.length; i++)
{
document.getElementById(els[i].id).innerHTML = new_value;
}
}
</script>
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