I have a question I have simple JavaScript that do some basic stuff to a number from input. I have a question how can I make variable that will always track the new input value for example if I enter 123 and click on some of the following buttons I get the result, but if I now enter new number for example 54321 and click again on some of the buttons I start from the previous value. How can I make my variable change every time a new value is entered or changed ? Here is my code:
var number = document.getElementById("number");
var numberValue = number.value;
console.log(numberValue);
function plus() {
number.value = ++numberValue;
}
function minus() {
number.value = --numberValue;
}
function flip() {
var temp = numberValue;
var cifra, prevrten = 0;
while (temp > 0) {
cifra = temp % 10;
prevrten = (prevrten * 10) + cifra;
temp = temp / 10 | 0;
}
number.value = prevrten;
}
window.onload = function() {
number.value = "";
}
<div>
<input type="text" id="number" id="output" onload="restart();">
<input type="button" value="<" onclick="minus();">
<input type="button" value=">" onclick="plus();">
<input type="button" value="FLIP" onclick="flip();">
<input type="button" value="STORE" onclick="store();">
<input type="button" value="CHECK" onclick="check();">
</div>
I suggest you use a type="number" and case the value to number - her I use the unary plus to do so
You will need to read the value in all functions
let numberValue = 0;
function store() {}
function check() {}
function plus() {
numberValue = +number.value;
number.value = ++numberValue;
}
function minus() {
numberValue = +number.value;
number.value = --numberValue;
}
function flip() {
let numberValue = +number.value;
var cifra, prevrten = 0;
while (numberValue > 0) {
cifra = numberValue % 10;
prevrten = (prevrten * 10) + cifra;
numberValue = numberValue / 10 | 0;
}
number.value = prevrten;
}
window.addEventListener("load", function() {
let number = document.getElementById("number");
number.value = 0;
})
<div>
<input type="number" id="number" id="output" onload="restart();">
<input type="button" value="<" onclick="minus();">
<input type="button" value=">" onclick="plus();">
<input type="button" value="FLIP" onclick="flip();">
<input type="button" value="STORE" onclick="store();">
<input type="button" value="CHECK" onclick="check();">
</div>
Try using onChange="".
<input type="text" id="number" id="output" onload="restart();" onChange="updateVal();">
function updateVal() {
numberValue = number.value;
}
I would suggest, for something like this, it would be much easier to use React JS or another framework with state.
Related
The output in the result field is showing NaN for the grandTotal function in the following JavaScript and HTML codes. Please assist to identify the error.
function firstSum(){
subPay=()=>{
let comPay = document.getElementById('totPay').value;
if (comPay > 215000){return (comPay - 215000)*0.25;}
else {return comPay*0.15;}
}
document.getElementById('result1').value = subPay();
}
groPay=()=>{
groEstimate=()=>{
let comPay = document.getElementById('totPay').value;
if (comPay > 220000){return (comPay - 220000)*0.33;}
else {return comPay*0.16;}
}
document.getElementById('result2').value = groEstimate();
}
function grandTotal(){
var allPay;
allPay = firstSum() + groPay();
document.getElementById('result').value = allPay;
}
<form>
<input id="totPay" type="number" placeholder = "groPymt">
<input type = "button" onclick = "grandTotal()" value = "Submit">
<div><input type="text" class="totsum" id="result1"></div>
<div><input type="text" class="totsum" id="result2"></div>
<div>Result: <input type="text" id="result"></div><br><br>
</form>
You should either return the values at the end of firstSum and groPay or change grandTotal to something like
function grandTotal(){
firstSum(); groPay();
const fs = document.getElementById('result1').value;
const gp = document.getElementById('result2').value;
document.getElementById('result').value = fs + gp;
}
i want to calculate the total of the numbers entered by the user. After a user has added item name and the amount, i want to display the total. How can i do this? i just need to display the total.
For example
item name : 10
item name : 5
total = 15
http://jsfiddle.net/81t6auhd/
<body>
<header>
<h1>Exercise 5-2</h1>
</header>
<p>Item: <input type="text" id="item" size="30">
<p>Amount: <input type="text" id="amount" size="30">
<p><span id="message">*</span>
<p><input type="button" id="addbutton" value="Add Item" onClick="processInfo();">
<script>
var $ = function(id) {
return document.getElementById(id);
};
var myTransaction = [];
function processInfo ()
{
var myItem = $('item').value;
var myAmount = parseFloat($('amount').value);
var myTotal = myItem + ":" + myAmount;
var myParagraph = $('message');
myParagraph.innerHTML = "";
myTransaction.push(myTotal);
myParagraph.innerHTML += myTransaction.join("<br>");
};
(function () {
$("addbutton").onclick = processInfo;
})();
</script>
</body>
you have to stored the previous value somewhere in memory to be able to reuse it at next iteration
one proposal can be to stored it in dataset of the field
if ($('amount').dataset.previous) {
myAmount += parseFloat($('amount').dataset.previous);
}
$('amount').dataset.previous = myAmount
var $ = function(id) {
return document.getElementById(id);
};
var myTransaction = [];
function processInfo ()
{
var myItem = $('item').value;
var myAmount = parseFloat($('amount').value);
if ($('amount').dataset.previous) {
myAmount += parseFloat($('amount').dataset.previous);
}
$('amount').dataset.previous = myAmount;
var myTotal = myItem + ":" + myAmount;
var myParagraph = $('message');
myParagraph.innerHTML = "";
myTransaction.push(myTotal);
myParagraph.innerHTML += myTransaction.join("<br>");
};
(function () {
$("addbutton").onclick = processInfo;
})();
<p>Item: <input type="text" id="item" size="30">
<p>Amount: <input type="text" id="amount" size="30">
<p><span id="message">*</span>
<p><input type="button" id="addbutton" value="Add Item" onClick="processInfo();">
my code calculates the AVG or MAX of an input set of numbers, I want the user to check on a checkbox list that contains AVG and MAX for desired output but I couldn't figure out doing it.
if I put an input of "2,4" without check listing the output is both AVG and MAX which is 3 4, I tried to checklist for only AVG or MAX outcome but it didn't work.
I have checked both function calculateAVG() & calculateMAX() and they produce correct output
function proccesFloat(flt) {
var splitFloat = flt.split(",");
for (x in splitFloat) {
splitFloat[x] = parseFloat(splitFloat[x]);
}
return splitFloat;
}
function calculateAVG(setNum) {
let total = 0;
var numInput = document.getElementById("setNum").value;
var result = 0;
var avg = proccesFloat(numInput);
for (let i = 0; i < avg.length; i++) {
total += avg[i];
}
result = total / avg.length;
document.getElementById('outputAVG').innerHTML = result;
}
function calculateMAX(setNum) {
var numInput = document.getElementById("setNum").value;
var numarry = proccesFloat(numInput);
var max = 0;
for (let i = 0; i < numarry.length; i++) {
if (numarry[i] > max) {
max = numarry[i];
}
}
document.getElementById('outputMAX').innerHTML = max;
}
function calculate() {
var checkBox = document.getElementsByTagName("check");
if (checkBox[0].checked) {
calculateAVG(document.getElementById("setNum"));
}
if (checkBox[0].checked) {
calculateMAX(document.getElementById("setNum"));
} {
alert('please choose formula')
return false;
}
}
<header>
<input type="Numbers" id="setNum" placeholder="Enter Set of Numbers">
<br>
<button onclick="calculate()" id="btn1">calculate</button>
<output id="outputAVG"></output>
<output id="outputMAX"></output>
<form method="post">
<fieldset>
<legend>Formula To Calculate?</legend>
<input type="checkbox" id="avg" name="check" onclick="calculate()">AVG<br>
<input type="checkbox" id="max" name="check" onclick="calculate()">MAX<br>
<br>
</fieldset>
</form>
</header>
Count the checked and then look at the IDs.
I also suggest you wrap in a form and use the submit event
I made a few more changes to simplify the code
Let the functions do one thing and use the event to bring them together
const proccesFloat = flt => flt.split(",").map(fl => +fl); // cast to float
const calculateAVG = setNum => {
const arr = proccesFloat(setNum);
const total = arr.reduce((a, b) => a + b)
return total / arr.length;
}
const calculateMAX = setNum => Math.max(...proccesFloat(setNum));
document.getElementById("calcForm").addEventListener("submit", function(e) {
e.preventDefault(); // stop submission
const chks = document.querySelectorAll("[name=check]:checked")
if (chks.length === 0) {
alert('please choose formula')
return
}
if (document.getElementById("avg").checked) {
document.getElementById('outputAVG').innerHTML = calculateAVG(document.getElementById("setNum").value);
}
if (document.getElementById("max").checked) {
document.getElementById('outputMAX').innerHTML = calculateMAX(document.getElementById("setNum").value);
}
})
<header>
<form id="calcForm">
<input type="Numbers" id="setNum" placeholder="Enter Set of Numbers">
<br>
<button type="submit">calculate</button>
<output id="outputAVG"></output>
<output id="outputMAX"></output>
<fieldset>
<legend>Formula To Calculate?</legend>
<input type="checkbox" id="avg" name="check">AVG<br>
<input type="checkbox" id="max" name="check">MAX<br>
<br>
</fieldset>
</form>
</header>
I have this issue where running a for loop between some ranges of numbers does not work? The loop literally just does not execute, and I really can't explain why this occurs for some number ranges, but not others. It seems that this only occurs in ranges where the upper value is < 100, and the lower is >=0. For example 20-100 does not work, yet 40-90 does. I've removed a lot of the code (mainly value validation things) that doesn't need to be included, as my only real issue is as to why this loop doesn't work.
I really don't even know what to try, I can't understand why calling createTable(20,100) doesn't execute the loop, whilst createTable(40,90) does...
I should also mention that this only occurs when clicking the "convert" button.
To try this yourself, enter 20 as the lower value, 100 as the upper value, select "Celsius → Fahrenheit" and click convert.
var lowerValue = document.getElementById("lower");
var upperValue = document.getElementById("upper");
var celsiusCheckBox = document.getElementById("celsius");
var fahrenheitCheckBox = document.getElementById("fahrenheit");
var submitButton = document.getElementById("submit");
function onButtonClicked() {
createTable(lowerValue.value, upperValue.value)
}
function createTable(lower, upper) {
for(let i = lower; i <= upper; i++ ) {
console.log(i);
}
}
function checkCheckBox(element) {
if (element.id == "celsius" && fahrenheitCheckBox.checked) {
fahrenheitCheckBox.checked = false;
} else if (element.id == "fahrenheit" && celsiusCheckBox.checked) {
celsiusCheckBox.checked = false;
}
}
<!DOCTYPE html>
<html lang="en">
<label>Lower value</label>
<input type="text" id="lower">
<label>Upper value*</label>
<input type="text" id="upper">
<label>Celsius → Fahrenheit</label>
<input type="checkbox" id="celsius" onclick="checkCheckBox(this)">
<label>Fahrenheit → Celsius</label>
<input type="checkbox" id="fahrenheit" onclick="checkCheckBox(this)">
<button type="button" id="submit" onclick="onButtonClicked()">Convert</button>
<body>
</body>
</html>
Any help would be greatly appreciated.
This happens because you are passing strings to the function and "100" is < than "20" since it starts with 1.
Use
function onButtonClicked() {
const lower = parseInt(lowerValue.value, 10);
const uppdate = parseInt(upperValue.value, 10);
createTable(lowerValue.value, upperValue.value)
}
Updated snippet
var lowerValue = document.getElementById("lower");
var upperValue = document.getElementById("upper");
var celsiusCheckBox = document.getElementById("celsius");
var fahrenheitCheckBox = document.getElementById("fahrenheit");
var submitButton = document.getElementById("submit");
function onButtonClicked() {
const lower = parseInt(lowerValue.value, 10);
const upper = parseInt(upperValue.value, 10);
createTable(lower, upper)
}
function createTable(lower, upper) {
for (let i = lower; i <= upper; i++) {
console.log(i);
}
}
function checkCheckBox(element) {
if (element.id == "celsius" && fahrenheitCheckBox.checked) {
fahrenheitCheckBox.checked = false;
} else if (element.id == "fahrenheit" && celsiusCheckBox.checked) {
celsiusCheckBox.checked = false;
}
}
<label>Lower value</label>
<input type="text" id="lower">
<label>Upper value*</label>
<input type="text" id="upper">
<label>Celsius → Fahrenheit</label>
<input type="checkbox" id="celsius" onclick="checkCheckBox(this)">
<label>Fahrenheit → Celsius</label>
<input type="checkbox" id="fahrenheit" onclick="checkCheckBox(this)">
<button type="button" id="submit" onclick="onButtonClicked()">Convert</button>
The values are received as strings in createTable function, Convert them to integers and try, it will work.
var lowerValue = document.getElementById("lower");
var upperValue = document.getElementById("upper");
var celsiusCheckBox = document.getElementById("celsius");
var fahrenheitCheckBox = document.getElementById("fahrenheit");
var submitButton = document.getElementById("submit");
function onButtonClicked() {
createTable(lowerValue.value, upperValue.value)
}
function createTable(lower, upper) {
lower = parseInt(lower);
upper = parseInt(upper);
for(let i = lower; i <= upper; i++ ) {
console.log(i);
}
}
function checkCheckBox(element) {
if (element.id == "celsius" && fahrenheitCheckBox.checked) {
fahrenheitCheckBox.checked = false;
} else if (element.id == "fahrenheit" && celsiusCheckBox.checked) {
celsiusCheckBox.checked = false;
}
}
<!DOCTYPE html>
<html lang="en">
<label>Lower value</label>
<input type="text" id="lower">
<label>Upper value*</label>
<input type="text" id="upper">
<label>Celsius → Fahrenheit</label>
<input type="checkbox" id="celsius" onclick="checkCheckBox(this)">
<label>Fahrenheit → Celsius</label>
<input type="checkbox" id="fahrenheit" onclick="checkCheckBox(this)">
<button type="button" id="submit" onclick="onButtonClicked()">Convert</button>
<body>
</body>
</html>
I created two input fields where they should substract from each other keeping a max value at 100.
Currently it substracted value is shown in the second value. I want it to be interchangeable. Irrespective of whether I put in first or second input field, the answer shows in the other.
Could someone help?
function updateDue() {
var total = parseInt(document.getElementById("totalval").value);
var val2 = parseInt(document.getElementById("inideposit").value);
// to make sure that they are numbers
if (!total) { total = 0; }
if (!val2) { val2 = 0; }
var ansD = document.getElementById("remainingval");
ansD.value = total - val2;
var val1 = parseInt(document.getElementById("inideposit").value);
// to make sure that they are numbers
if (!total) { total = 0; }
if (!val1) { val1 = 0; }
var ansD = document.getElementById("remainingval");
ansD.value = total - val1;
}
<input type="hidden" id="totalval" name="totalval" value="100" onchange="updateDue()">
<div>
Enter Value:
<input type="text" name="inideposit" class="form-control" id="inideposit" onchange="updateDue()">
</div>
<div>
Substracted:
<input type="text" name="remainingval" class="form-control" id="remainingval" onchange="updateDue()">
</div>
The simple way to achieve this would be to group the inputs by class and attach a single event handler to them. Then you can take the entered value from 100, and set the result to the field which was not interacted with by the user. To do that in jQuery is trivial:
$('.updatedue').on('input', function() {
var total = parseInt($('#totalval').val(), 10) || 0;
var subtracted = total - (parseInt(this.value, 10) || 0);
$('.updatedue').not(this).val(subtracted);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="hidden" id="totalval" name="totalval" value="100" />
<div>
Enter Value:
<input type="text" name="inideposit" class="updatedue form-control" id="inideposit" />
</div>
<div>
Subtracted:
<input type="text" name="remainingval" class="updatedue form-control" id="remainingval" />
</div>
You can easily validate this so that outputs < 0 and > 100 can be discounted, if required.
Edit your code as below
function updateDue(box) {
var total = parseInt(document.getElementById("totalval").value);
if(box == 1){
var val = parseInt(document.getElementById("inideposit").value);
// to make sure that they are numbers
if (!total) { total = 0; }
if (!val) { val = 0; }
var ansD = document.getElementById("remainingval");
ansD.value = total - val;
}else if(box == 2){
var val = parseInt(document.getElementById("remainingval").value);
// to make sure that they are numbers
if (!total) { total = 0; }
if (!val) { val = 0; }
var ansD = document.getElementById("inideposit");
ansD.value = total - val;
}
}
<input type="hidden" id="totalval" name="totalval" value="100" onchange="updateDue(0)">
<div>
Enter Value:
<input type="text" name="inideposit" class="form-control" id="inideposit" onchange="updateDue(1)">
</div>
<div>
Substracted:
<input type="text" name="remainingval" class="form-control" id="remainingval" onchange="updateDue(2)">
</div>