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>
Related
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.
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 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>
here's my code, brand new to coding trying to get the box "points" to return the sum of pointSum if "Ben" is typed into the box "winner". Just trying to work on some basics with this project. Attempting to make a bracket of sorts
<HTLML>
<head>
<script>
var pointSum = 0;
var firstRound = 20;
var secondRound = 50;
var thirdRound = 100;
var fourthRound = 150;
var fifthRound = 250;
var finalRound = 300;
var winnerOne = false;
var winnerTwo = false;
var winnerThree = false;
var winnerFour = false;
var winnerFive = false;
var winnerSix = false;
if (winnerOne = true){
pointSum+=firstRound
} else if (winnerTwo = true){
pointSum+=secondRound
} else if (winnerThree = true){
pointSum+=thirdRound
} else if (winnerFour = true){
pointSum+=fourthRound
} else if (winnerFive = true){
pointSum+=fifthRound
} else if (winnerSix = true){
pointSum+=finalRound
else
function tally() {if document.getElementById('winner') == "Ben" { winnerOne = true;
}
pointSum=document.getElementById("points").value;
}
</script>
</head>
<body>
<form>
Winner:
<input type="text" name="winner" id="winner" size="20">
Points:
<input type="text" name="points" id="points" size="20">
Submit
<button type= "button" onclick="tally()">Tally points</button>
</form>
</body>
</html>
UPDATE***** new code, getting better, not returning console errors but still not getting anything in the "points" box upon clicking tally
<HTLML>
<head>
<script>
var pointSum = 0;
var firstRound = 20;
var secondRound = 50;
var thirdRound = 100;
var fourthRound = 150;
var fifthRound = 250;
var finalRound = 300;
var winnerOne = false;
var winnerTwo = false;
var winnerThree = false;
var winnerFour = false;
var winnerFive = false;
var winnerSix = false;
function tally() {
var winner = document.getElementById("winner").value;
var firstWinner = "Ben";
if (winner == firstWinner){
winnerOne == true;
}
pointSum = document.getElementById("points").value;
}
if (winnerOne == true){
pointSum+=firstRound;
} else if (winnerTwo){
pointSum+=secondRound;
} else if (winnerThree){
pointSum+=thirdRound;
} else if (winnerFour){
pointSum+=fourthRound;
} else if (winnerFive){
pointSum+=fifthRound;
} else if (winnerSix){
pointSum+=finalRound;
}
</script>
</head>
<body>
<form>
Winner:
<input type="text" name="winner" id="winner" size="20">
Points:
<input type="text" name="points" id="points" size="20">
Submit
<button type= "button" onclick="tally()">Tally points</button>
</form>
<div class="updatePoints">
</div>
</body>
</html>
Your code has a few mistakes, lets change it a little bit!
First, you need to access 'value' atribbute of your winner element in your if statement, and surround all the statement in parenthesis
function tally() {
if (document.getElementById('winner').value == "Ben"){
winnerOne = true;
}
pointSum = document.getElementById("points").value;
}
Second, you use '==' to make comparison, you are using '=', it means that you are assign true to variables, and you're forgetting to put ';' at the end of lines! change this part:
if (winnerOne == true){
pointSum+=firstRound;
}
put all of your if/else like the example above!
Hint: when you are using if statement you can use like this:
if (winnerOne){ //you can omit == true, because if winnerOne is true, it will enter ind the if statement
//will enter here if winnerOne is true
}
if (!winnerOne){ //you can omit == false, because if winnerOne is not true, it will enter ind the if statement
//will enter here if winnerOne is false
}
You also have a left over else at the end of your if check which is invalid. You need to end the last else if statement with the };.
Are you trying to out put the text somewhere? I don't see any code that is handling this - you may want to add some HTML that will update like so:
<div class="updatePoints">
// leave empty
</div>
Then within your JavaScript you can always add some code to update the .updatePoints
var points = document.getElementByClass('updatePoints');
points.innerHTML = pointSum.value;
Have add some lines in your code and modify it with some comments. Can try at https://jsfiddle.net/8fhwg6ou/. Hope can help.
<HTLML>
<head>
<script>
var pointSum = 0;
var firstRound = 20;
var secondRound = 50;
var thirdRound = 100;
var fourthRound = 150;
var fifthRound = 250;
var finalRound = 300;
var winnerOne = false;
var winnerTwo = false;
var winnerThree = false;
var winnerFour = false;
var winnerFive = false;
var winnerSix = false;
function tally() {
var winner = document.getElementById("winner").value;
var firstWinner = "Ben";
if (winner == firstWinner){
winnerOne = true; // Use only one = symbol to assign value, not ==
pointSum = Number(document.getElementById("points").value); // moved from outside and convert to number
// This code will update point in Points box
document.getElementById("points").value = tally_pointsum(pointSum);
// The codes below will add the text in div, just remove the + sign if you don't like
document.getElementById("updatePoints").innerHTML += (tally_pointsum(pointSum) - pointSum) + " points added<br />";
}
}
// Wrap codes below become a function, lets call it tally_pointsum:
function tally_pointsum(pointSum) {
if (winnerOne == true){
pointSum+=firstRound;
} else if (winnerTwo){
pointSum+=secondRound;
} else if (winnerThree){
pointSum+=thirdRound;
} else if (winnerFour){
pointSum+=fourthRound;
} else if (winnerFive){
pointSum+=fifthRound;
} else if (winnerSix){
pointSum+=finalRound;
}
return pointSum; //return the sum to caller
}
</script>
</head>
<body>
<form>
Winner:
<input type="text" name="winner" id="winner" size="20">
Points:
<input type="text" name="points" id="points" size="20">
Submit
<button type= "button" onclick="tally()">Tally points</button>
</form>
<!-- change class="updatePoints" to id="updatePoints" for document.getElementById("updatePoints") -->
<div id="updatePoints">
</div>
Happy coding.
How to check value in input using loop for with onchange using javascript ?
first, When user fill char. It's will be show Your Price must be a number.
And if user fill number less than 1.5 It's will show Your Price must be at least $1.50 USD.
and click Add more link to add input.
I try my code , but not work, how can i do that ?
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<form onsubmit="return checkform(this);">
Add more
<div id="p_scents_price">
<p>
<label>
<input type="text" class="price" id="price0" size="20" name="price[]" onchange="myFunction0()"/><p id="demo0"></p>
</label>
</p>
</div>
<input type="submit" name="submit" value="OK">
</form>
<script>
var list = document.querySelectorAll(".price");
for (z = 0; z < list.length; ++z) {
function myFunction'+z+'() {
var x = document.getElementById("price'+z+'").value;
var y = isNaN(x);
if(y === true)
{
document.getElementById("demo'+z+'").innerHTML = "Your Price must be a number.";
}
else
{
if(x < 1.5)
{
document.getElementById("demo'+z+'").innerHTML = "Your Price must be at least $1.50 USD.";
}
else
{
document.getElementById("demo'+z+'").innerHTML = "";
}
}
}
}
}
</script>
<script>
$(function() {
var scntDiv = $('#p_scents_price');
var i = 1;
$('#addScnt_price').live('click', function() {
$('<p><label><input type="text" class="price" id="price'+i+'" size="20" name="price[]" onchange="myFunction'+i+'()"/>Remove<p id="demo'+i+'"></p></label></p>').appendTo(scntDiv);
i++;
return false;
});
$('#remScnt_price').live('click', function() {
if( i > 2 ) {
$(this).parents('p').remove();
}
return false;
});
});
</script>