I'm working on a small project about the Collatz conjecture.
In this project i want to apply the formula " times 3 plus one" when the number is odd and devide a number when its even.
i want to keep looping this until the number is 1 and show not only how many steps it took but also display all the numbers it goes through.
i've gotten quite far i think but i have trouble displaying all the steps the loop goes through.
here is my code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Collatz Conjecture</title>
<script>
function findOddEven() {
var num = document.getElementById('num').value;
let i = 0;
while (num != 1) {
if (num % 2 == 0) {
num = num / 2; /*even*/
} else {
num = (num * 3) + 1; /*odd*/
console.log(num) }
i++
document.getElementById('result').innerHTML = "Result is " + num + " found in " + i + " runs";
}
}
</script>
</head>
<body>
<form method="post">
<small>Number:</small><input type="text" id="num" name="num" min="0" /><input type="button" value="submit"
onclick="findOddEven()" name="find" />
<div style="margin-top: 10px;" id="result"></div>
</form>
</body>
</html>
You can store the numbers in the array and display them at the end. You can also move the .innerHTML out of the loop since this only needs to be done when the loop is finished.
I've used join to turn the array into a comma seperated string.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Collatz Conjecture</title>
<script>
function findOddEven() {
var num = document.getElementById('num').value;
let steps = [num]; // Store starting number
let i = 0;
while (num != 1) {
if (num % 2 == 0) {
num = num / 2; /*even*/
} else {
num = num * 3 + 1; /*odd*/
}
steps.push(num); // Add changed number to the array
i++;
}
document.getElementById('result').innerHTML =
'Result is ' + num + ' found in ' + i + ' runs. Steps taken: ' + steps.join(', ');
}
</script>
</head>
<body>
<form method="post">
<small>Number:</small
><input type="text" id="num" name="num" min="0" /><input
type="button"
value="submit"
onclick="findOddEven()"
name="find"
/>
<div style="margin-top: 10px" id="result"></div>
</form>
</body>
</html>
Is your problem not seeing all numbers? If so, your console.log is inside the else statement. To see all numbers you shall move it outside the if else statement.
Related
In the code below 'len' is the length of text in a tag, the user enters a letter in a textbox, and inside 'result', with the help of .indexof() I am storing the index number of the letter present in the paragraph and then printing that letter in another tag.
But this loop only runs once whereas I want it to run until the statement in the while loop is true.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>HTML 5 Boilerplate</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<p>Find letter:</p>
<form id="chk" method="post">
<label for="scen">Enter a scentence</label>
<!--<input type="text" name="scen" id="scen" placeholder="Enter a scentence">-->
<p id='scen'>Hello my friend</p>
<br><br>
<label for="letter">Enter the letter</label>
<input type="text" name="letter" id="letter" placeholder="Enter a letter" min="1">
<br>
<button type="button" onClick="myFunction()">Submit</button>
</form>
<p id="demo"></p>
<p id="demo2"></p>
<p id="demo3"></p>
<script >
function myFunction(){
var scen = document.getElementById('scen').innerHTML;
var spa = ' ';
var scen1 = scen.split(" ").join(spa);
var letter = document.getElementById('letter').value;
let err = "The letter does not exist in the sentence"
let result = scen.indexOf(letter);
var len = scen.length;
var a = 3;
var k = 0
for(var i = 0; i < scen1.length; i++)
{
document.getElementById('demo').innerHTML += '<span id="w' + i + '">' + scen1[i] + '</span>'
}
while(k <= len){
if(result>=0){
document.getElementById('demo3').innerHTML = scen.substring(result,result+1);
document.getElementById('demo').innerHTML = len;
}
else{
document.getElementById('demo2').innerHTML = err;
a--;
document.getElementById('demo').innerHTML = a;
break;
}
if(a==0){
window.alert('game over');
}
k++;
}
}
</script>
</body>
</html>
Because of the break condition in Else part of your code is making code to exit from loop.
Please see below code and comments which I have added in your code... and let me know...
function myFunction() {
var scen = document.getElementById('scen').innerHTML;
var spa = ' ';
var scen1 = scen.split(" ").join(spa);
var letter = document.getElementById('letter').value;
let err = "The letter does not exist in the sentence"
let result = scen.indexOf(letter);
var len = scen.length;
var a = 3;
var k = 0
for (var i = 0; i < scen1.length; i++) {
document.getElementById('demo').innerHTML += '<span id="w' + i + '">' + scen1[i] + '</span>'
}
while (k <= len) {
//console.log("Loop iteration ->",k); /*you can uncomment this statement to debug the loop is working or not *?
if (result >= 0) {
document.getElementById('demo3').innerHTML = scen.substring(result, result + 1);
document.getElementById('demo').innerHTML = len;
} else {
document.getElementById('demo2').innerHTML = err;
a--;
document.getElementById('demo').innerHTML = a;
// break; /* Commented this line so that your loop will run*/
}
if (a == 0) {
window.alert('game over');
}
k++;
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>HTML 5 Boilerplate</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<p>Find letter:</p>
<form id="chk" method="post">
<label for="scen">Enter a scentence</label>
<!--<input type="text" name="scen" id="scen" placeholder="Enter a scentence">-->
<p id='scen'>Hello my friend</p>
<br><br>
<label for="letter">Enter the letter</label>
<input type="text" name="letter" id="letter" placeholder="Enter a letter" min="1">
<br>
<button type="button" onClick="myFunction()">Submit</button>
</form>
<p id="demo"></p>
<p id="demo2"></p>
<p id="demo3"></p>
</body>
</html>
Remove the break. It's breaking you out of the loop.
I have created a number guessing game from 1 to 10, Here is the Js code but i am unable to get the output.
Here is my code:
var enterButton = document.getElementById('enterButton');
var againButton = document.getElementById('againButton');
var output = document.getElementById('outputText');
var randomNumber = Math.ceil(Math.random() * 10);
function checkNumber() {
var input = document.getElementById('userInput').value;
if (input == randomNumber) {
alert.innerHTML = "Your guess is right " + "," + ",it was " + randomNumber;
} else if (number > randomNumber && input < 10) {
alert.innerHTML = "Your guess is to high";
} else if (input < randomNumber && input > 1) {
alert.innerHTML = "Your guess is too low ";
} else if (isNaN(input)) {
alert.innerHTML = "Invalid operator";
}
enterButton.addEventListener('click', checkNumber);
againButton.addEventListener('click', function () {
})
}
Here it the html code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="sylesheet" href="index.css" />
</head>
<body>
<script src="script.js">
</script>
</body>
<div id="container">
<p> Guess a number between 1-10</p>
<p id="outputtext"> Enter the number below </p>
<input id="userInput">
<button id="enterButton">Enter</button>
<button id="aginButton">Try again</button>
</div>
</html>
There a couple of issues in your code, first in the html code, you got the id of again button wrong, it should be like this:
<button id="againButton">Try again</button>
Then in the JS code, you should move the two addEventListener() methods out of the checkNumber() function definition. Most importantly, you set the input variable to be the value of the input html element. The value property returns string, and then you compare randomNumber with a string which will not work as expected.
Also, the alert.innerHTML will not work. alert() is a global method which will accepts a string type as its parameter. Please see the JS code corrected below:
var enterButton = document.getElementById('enterButton');
var againButton = document.getElementById('againButton');
var output = document.getElementById('outputText');
var randomNumber = Math.ceil(Math.random() * 10);
function checkNumber() {
var input = parseInt(document.getElementById('userInput').value);
if (input === randomNumber) {
window.alert("Your guess is right it was " + randomNumber)
} else if (input > randomNumber && input < 10) {
window.alert("Your guess is to high");
} else if (input < randomNumber && input > 1) {
window.alert("Your guess is too low ");
} else if (isNaN(input)) {
window.alert("Invalid operator");
}
}
enterButton.addEventListener('click', checkNumber);
againButton.addEventListener('click', function () {
})
You should also put your script tag right before the ending </body> tag for it to be able to do its tasks on the DOM elements. Take a look here:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="sylesheet" href="index.css" />
</head>
<body>
<div id="container">
<p> Guess a number between 1-10</p>
<p id="outputtext"> Enter the number below </p>
<input id="userInput">
<button id="enterButton">Enter</button>
<button id="againButton">Try again</button>
</div>
<script src="script.js"></script>
</body>
</html>
There were a few errors in your script. Check out this fixed version.
UPDATE
I now put the <script> element ahead of the <body> element to demonstrate the necessitiy of the window.onload=function(){...}. My whole script is now placed within this function as otherwise, the DOM elements the script refers to, would not yet exist.
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="sylesheet" href="index.css" />
<script>
window.onload=function(){
const [form1,againButton,output,inp]="container,againButton,outputText,userInput".split(",")
.map(id=>document.getElementById(id)), setrndm=_=>randomNumber=Math.ceil(Math.random()*10);
var randomNumber;
setrndm();
form1.addEventListener('submit', checkNumber);
againButton.addEventListener('click', setrndm);
function checkNumber(ev) {
ev.preventDefault(); inp.select();
var input = inp.value;
if (input == randomNumber) {
console.log("Your guess is right, it was " + randomNumber);
} else if (input > randomNumber && input < 11) {
console.log("Your guess is to high");
} else if (input < randomNumber && input > 0) {
console.log("Your guess is too low ");
} else if (isNaN(input)) {
console.log("Invalid operator");
}
}
};
</script>
</head>
<body>
<form id="container">
<p> Guess a number between 1-10</p>
<p id="outputtext"> Enter the number below </p>
<input id="userInput">
<button id="enterButton">Enter</button>
<button type="button" id="againButton">Try again</button>
</form>
</body>
I am creating a reservation program where the test2.asp page returns the result according to the date sent from the test1.asp page. I don't know where I'm doing wrong, but it only returns 2x result. It doesn't matter if I add or subtract the value. It always returns the correct result only 2 times and then stops.
Page test1.asp
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<title></title>
</head>
<body>
<script type="text/javascript">
function changeOfmonth(posun) {
var monNum = Number($("#monCal").val());
var yearNum = Number($("#yearCal").val());
if (posun == 1) { $("#monCal").val(monNum + 1) };
if (posun == 2) { $("#monCal").val(monNum - 1) };
if ($("#monCal").val() == 13) {
$("#yearCal").val(yearNum + 1);
$("#monCal").val(1);
};
if ($("#monCal").val() == 0) {
$("#yearCal").val(yearNum - 1);
$("#monCal").val(12);
};
var sendKal = $("#monCal").val() + ',' + $("#yearCal").val();
$.get('test2.asp?sendMonYear=' + sendKal, function (vystup) {
$("#testResult").html(vystup);
})
}
</script>
<div style="width:100%;margin-left:auto;margin-right:auto;">
<input name="butMon1" onclick="changeOfmonth(2);" type="button" id="plusMonth" value="←" />
<input name="butMon3" onclick="changeOfmonth(1);" type="button" id="minusMonth" value="→" />
</div>
<input id="monCal" type="text" value="7" /><input id="yearCal" type="text" value="2022" /><br/>
<div id="testResult"></div>
</body>
</html>
Page test2.asp
<% response.write "<br> Result: " & Request.QueryString("sendMonYear") %>
From input i enter numbers in the input text, then i have 5 buttons that have functions on them i tried to make the first button to minus the number by 1 but i don't know when i click the number get -1 but it doesn't show changes to the input box. How can i fix this i mean don't know how to do it because i tried using number.innerHTML = number-=1 but it doesn't work ? Here is my html and javascript code:
var number = document.getElementById("number");
number = number.value;
function minus() {
number.value = number -= 1;
console.log(number);
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div>
<input type="text" id="number" id="output">
<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>
</body>
</html>
Ok let's think logically here
var number = document.getElementById("number");
number = number.value;
function minus() {
number.value = number -= 1;
console.log(number);
}
first you're assigning the HTML ELEMENT itself to the var "number", then you're changing the value of the "number" var to the value of the HTML element, so then number.value = number - 1 is trying to set the property of "value" of a number object, which doesn't make sense, because it's not connected to the HTML element anymore
Just make two variables it should be fine, like
var number = document.getElementById("number");
var numberValue = number.value;
function minus() {
numberValue = number.value;
number.value = numberValue -= 1;
console.log(number,numberValue);
}
or alternatively, you only need one variable total, and you don't need to reassign it to "number.value", but the only thing is that this way there's no guarantee that number.value is a number at all, but when you set it to a variable first, like above, you can check if(!isNaN) or something similar, but still, if we want to assume only numbers will ever be entered, we can do something like
var number = document.getElementById("number");
function minus() {
number.value = number.value -= 1;
console.log(number,number.value);
}
Try this instead.
var number = document.getElementById("number");
function minus() {
number.value = number.value -= 1;
console.log(number);
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div>
<input type="text" id="number" id="output">
<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>
</body>
</html>
I have a problem with add auto Spaced in Input Tel.
I would like to add a 9-digit number so that every 3 digits take a break (spaces or pauses) like +880 111 222 333. Someone could explain how to achieve it?
function addSpace(){
var inputValue = document.getElementById("telInput").value;
var inputValueLength = inputValue.length;
if(inputValueLength == 3 || inputValueLength == 7){
document.getElementById("telInput").value = inputValue+" ";
}
}
<input type="tel" id="telInput" onkeypress="addSpace()">
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<form action="" method="GET">
<input type="tel" name="phone" id="phone" pattern="[0-9 -+()]{11,11}">
<input type="submit" value="Submit" >
</form>
</body>
</html>
<script>
let itemInput=document.querySelector('input[type=tel]') ;
itemInput.addEventListener('keypress',phone);
function phone()
{
let p=this.value;
if((p.length+1)%4==0 && p.length<9) this.value=p+" ";
}
</script>
XXX XXX XXX only accepts numbers that are 0-9 in this view.try one.
<!DOCTYPE html>
<html>
<head>
<script>
function inNumber(elm){
if (!elm.value) return
elm.value = elm.value.replace(/ /g, '')
}
function withSpaces(elm) {
if (!elm.value|| isNaN(elm.value) || elm.value.length < 3) return
elm.value = elm.value.replace(/\B(?=(\d{3})+(?!\d))/g, " ");;
}
</script>
</head>
<body>
<p>Enter any number value and press tab </p>
<input id="0" onblur="withSpaces(this)" onfocus="inNumber(this)">
</body>
</html>
JQuery:
<input type="tel" placeholder="123-456-7890" maxlength="12" id="phone" >
<script>
jQuery(document).ready(function() {
$("#phone").keyup(function() {
var number = $(this).val();
var lngth = number.length;
if (lngth == 3 || lngth == 7) {
$("#phone").val(number + "-") ;
} else if (lngth >12 ) {
$("#phone").val(number.slice(0,12));
}
})
});
</script>
Maybe maxlength="12" and else if (lngth >12 ) is redundant but it doesn't hurt either