I have this JS / HTML code. It is supposed to give you an input. When you click the button as many times as you wrote in the input then it the screen is supposed to say 'stop' but that's not happening and idk why. How can I fix this?
var text2
let count = 1;
var correct = 1;
function check() {
text2 = document.getElementById('questions').value;
correct = correct + 1;
count = count + 1;
if (count === text2) {
var score = "stop";
document.getElementById('div').innerHTML = score;
}
}
<p>how many?<input type="text" id="questions"></p>
<button onclick="check()" id='but'>ok</button>
<div id='div'></div>
Refactor your code like this:
<html>
<body>
<p>how many?<input type="text" id="questions"></p>
<button onclick="check()" id='div'>ok</button>
<div id='div'> </div>
<script>
var count = 0;
function check() {
let user_input = document.getElementById('questions').value;
if (++count === parseInt(user_input)) {
document.getElementById('div').innerHTML = "stop";
}
}
</script>
</body>
</html>
This shoud do the trick:
<html>
<body>
<p>how many?<input type="text" onInput="onInput()" id="questions"></p>
<button onclick="check()" id = 'but'> ok </button>
<div id = 'div'> </div>
<script>
var text2;
let count = 0
function onInput() {
var element = document.getElementById('questions');
//replace window
text2 = element.value;
}
function check(){
count = count + 1;
console.log(count);
if (count === parseInt(text2)){
var score = "stop";
document.getElementById('div').innerHTML = score;
}
}
</script>
</body>
</html>
You are using === to compare, which checks type before comparing. count is an integer and text2 is a String, so it will always return false. Instead, first parse text2 into an integer, then compare like so:
<html>
<body>
<p>how many?<input type="text" id="questions"></p>
<button onclick="check()" id='but'> ok </button>
<div id='div'> </div>
<script>
var text2
let count = 0;
var correct = 0;
function check() {
text2 = document.getElementById('questions').value;
correct = correct + 1;
count++;
if (count === parseInt(text2)) {
var score = "stop";
document.getElementById('div').innerHTML = score;
}
}
</script>
</body>
</html>
Or instead use == which only checks for value:
<html>
<body>
<p>how many?<input type="text" id="questions"></p>
<button onclick="check()" id='but'> ok </button>
<div id='div'> </div>
<script>
var text2
let count = 0;
var correct = 1;
function check() {
text2 = document.getElementById('questions').value;
correct = correct + 1;
count++;
if (count == text2) {
var score = "stop";
document.getElementById('div').innerHTML = score;
}
}
</script>
</body>
</html>
Related
The code below returns me 'even' or 'odd', but I have to always change, what to do for him to check 25 to 115 and show result in the body of the page?
<html>
<title>FrontPage</title>
</head>
<body>
<form method="post" name="Form1" onsubmit="Check();">
<input type="submit" value="Submit" name="bSubmit"></p>
</form>
<script type="text/javascript">
function Check() {
var n = "26";
var finish = n/2;
if(n & 1){
alert("Impar");
} else {
alert("Par");
}
alert(finish);
}
</script>
</body>
</html>
var btn = document.querySelector('#btn');
var result = document.querySelector('#result');
btn.addEventListener('click', function() {
for (var i = 25; i <= 115; i++) {
var li = document.createElement('li');
li.innerText = i.toString() + ' - ' + ((i & 1) ? 'Impar' : 'Par');
result.append(li);
}
});
<input id="btn" type="submit" value="Submit" name="bSubmit">
<ul id="result"></ul>
Just implement your code within a for-loop (since you know exactly how many iterations you need):
document.querySelector('#btnSubmit').addEventListener('click', function(e) {
var min = 25;
var max = 115;
var i;
for (i = min; i <= max; i += 1) {
console.log(check(i));
}
});
function check(n) {
var s = `${n} is `;
s += n % 2 === 0 ? "even" : "odd";
return s;
}
check();
<input id="btnSubmit" type="button" value="Check" />
You need to use the foor loop like so:
const append = str => document.getElementById('print').innerHTML += str;
document.getElementById('btn').addEventListener('click', function () {
for (let i = 25; i <= 115; i++) {
const result = i % 2 === 0 ? 'even' : 'odd';
append(`<p>Number ${i} is ${result}</p>`);
}
});
<button id="btn">Result</button>
<div id="print"></div>
I have two input fields and a button. When the user clicks the button, I want it to display the text the user wrote in the first input the amount of times the user wrote in the second input.
I understand you have to use a while loop for this. What am I doing wrong here?
<!DOCTYPE html>
<html>
<head>
<title>While Loop</title>
<script type="text/javascript">
window.onload = btn;
function btn() {
document.getElementById("btn").onclick = showText;
}
function showText() {
var text = "";
var inputOne = document.getElementById("txtBox").value;
var inputTwo = document.getElementById("numBox").value;
while (inputOne < inputTwo) {
text += inputOne;
inputOne++;
}
document.getElementById("showCode").innerHTML = text;
}
</script>
</head>
<body>
<input type="text" id="txtBox"><br/>
<input type="number" id="numBox"><br/>
<button type="button" id="btn">Click Me!</button>
<p id="showCode"></p>
</body>
</html>
Since inputOne is a text, you cannot increment it (you can't do inputOne++), instead, use another variable, let's call it i, to control the while loop:
window.onload = btn;
function btn() {
document.getElementById("btn").onclick = showText;
}
function showText() {
var text = "";
var inputOne = document.getElementById("txtBox").value;
var inputTwo = document.getElementById("numBox").value;
var i=1; // to control the loop
while (i <= inputTwo) { // i goes from 1 to inputTwo
text += inputOne;
i++;
}
document.getElementById("showCode").innerHTML = text;
}
<input type="text" id="txtBox"><br/>
<input type="number" id="numBox"><br/>
<button type="button" id="btn">Click Me!</button>
<p id="showCode"></p>
This is my solution
<!DOCTYPE html>
<html>
<head>
<title>While Loop</title>
<script type="text/javascript">
window.onload = btn;
var count = 0;
function btn() {
document.getElementById("btn").onclick = showText;
}
function showText() {
var text = "";
console.log("Text: "+text);
var inputOne = document.getElementById("txtBox").value;
console.log("Input One: "+inputOne);
var inputTwo = document.getElementById("numBox").value;
console.log("Input 2: "+inputTwo);
count=count+1;
console.log("Times: "+count);
document.getElementById("numBox").value = count;
document.getElementById("showCode").innerHTML = text;
}
</script>
</head>
<body>
<input type="text" id="txtBox"><br/>
<input type="number" id="numBox"><br/>
<button type="button" id="btn">Click Me!</button>
<p id="showCode"></p>
</body>
</html>
Instead of the while loop you can use a for loop like this:
for( let i = inputTwo; i>0; i--) {
text += inputOne;
}
Im trying to implement a logic whereby each time I click the button the count alternates between 1 and 0. In the following code the count is always 0 as each time I press the button the function sets the count to 0. Please help me out and thanks in advance
<html>
<head>
<script type="text/javascript">
function main(){
var button = document.getElementById('button');
count = 0;
if(button.onclick && count == 0){
alert(count);
count = 1;
}
else if(button.onclick && count == 1){
alert(count);
count = 0;
}
}
</script>
</head>
<body>
<button type="button" id="button" onclick="main()">Click Me!</button>
</body>
</html>
Declare count variable at global scope.
<html>
<head>
<script type="text/javascript">
var count = 0;
function main(){
var button = document.getElementById('button');
if(button.onclick && count == 0){
alert(count);
count = 1;
}
else if(button.onclick && count == 1){
alert(count);
count = 0;
}
}
</script>
</head>
<body>
<button type="button" id="button" onclick="main()">Click Me!</button>
</body>
</html>
Declare the button in global scope. And use the bitwise operator for toggling between 0 and 1 like this..
<script type="text/javascript">
var count = 0; //global scope
function main(){
var button = document.getElementById('button');
if(button.onclick){
alert(count);
count ^= 1; //bitwise operator
}
}
</script>
^ (Bitwise XOR) as a I/O toggler
each time you click the button, main() is called. and each time you call main() you're setting count to 0 to start. Place count outside your function scope.
I agree with Ataur's answer but you might want to consider a bool for this use case as best practise.
<html>
<head>
<script type="text/javascript">
var buttonIsOn = true;
function main(){
var button = document.getElementById('button');
if(button.onclick && buttonIsOn){
alert("turning button off");
buttonIsOn = false;
}
else { // no need to check again if using bool
alert("turning button on");
buttonIsOn = true;
}
}
</script>
</head>
<body>
<button type="button" id="button" onclick="main()">Click Me!</button>
</body>
</html>
You should set the count to 0 outside of the function.
<html>
<head>
<script type="text/javascript">
var count = 0;
function main(){
var button = document.getElementById('button');
if(button.onclick && count == 0){
alert(count);
count = 1;
}
else if(button.onclick && count == 1){
alert(count);
count = 0;
}
}
</script>
</head>
<body>
<button type="button" id="button" onclick="main()">Click Me!</button>
</body>
</html>
You need to hook click event with button and alternate between 0 & 1 on click.
function main() {
var button = document.getElementById('button');
var count = 0;
button.addEventListener("click", function() {
if (count == 0) {
alert(count);
count = 1;
}
else if (count == 1) {
alert(count);
count = 0;
}
});
}
Further make sure that main function is called on when document is in ready state or put function call to main right above closing of body tag. Something like this
<body>
<button type="button" id="button" >Click Me!</button>
<script>
main();
</script>
</body>
New to Javascript and HTML. In a nutshell, attempting to update score if user enters correct sum of random math problem. Not able to pass the answer of the problem to my function which checks if what the user entered is correct. I just want the score to increase by one. For some reason the function I am passing the parameter "score" to is not being recognized by it.
Here is a very quick example of my code. More concerned about the logic instead of the looks right now of the program. I know right now the score will not update correctly but the problem lies in the passing of the "answer" variable. I will easily work through the score increase once the function at least gets called. Thank you very much for your time!
<html>
<title></title>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body onload = "displayProblem()">
<script>
function displayProblem(){
var answer = (firstNum) + (secondNum);
var firstNum = (Math.floor(Math.random()*10) + 1);
var secondNum = (Math.floor(Math.random()*10) + 1);
document.getElementById("qstns").innerHTML = firstNum +" + " + secondNum +" = ";
}
function checkAnswer(){
var userAnswer = document.getElementById("answr").value;
if(userAnswer === answer){
updateScore();
console.log("score updated");
}
console.log("did not update score");
}
function displayNext(){
document.getElementById("next").style.display = "block";
}
function hideNext(){
document.getElementById("next").style.display = "none";
}
function updateScore(){
var score = 0;
score++;
document.getElementById("score").innerHTML = score;
}
function clearAnswer(){
document.getElementById("answr").value = " ";
}
</script>
<div id="main">
<div id="qstns">
</div>
</div>
<input type="text" id="answr">
Score: <label id="score"> 0 </label>
<button type="Sumbit" id="submit" onclick="displayNext(), checkAnswer ()">Check</button>
<button type="Submit" id="next" onclick="displayProblem(), hideNext(), clearAnswer()" style="display:none;">Next</button>
</body>
</html>
the prob is that every time you call the function "updateScore"
you reset the value of "score" to zero.
one way could be this: read the current score first than increase...
function updateScore(){
var score = pareseInt(document.getElementById("score").innerHTML);
score++;
document.getElementById("score").innerHTML = score;
}
or this: set score to "global" than increase...
var score = 0;
function updateScore(){
score++;
document.getElementById("score").innerHTML = score;
}
Try this:
<html>
<title></title>
<head>
</head>
<body onload="displayProblem()">
<script>
var answer;
var score=0;
function displayProblem(){
var firstNum = (Math.floor(Math.random()*10) + 1);
var secondNum = (Math.floor(Math.random()*10) + 1);
answer = (firstNum) + (secondNum);
document.getElementById("qstns").innerHTML = firstNum +" + " + secondNum +" = ";
}
function checkAnswer(){
var userAnswer = document.getElementById("answr").value;
if(userAnswer == answer)
updateScore();
}
function displayNext(){
document.getElementById("next").style.display = "block";
}
function hideNext(){
document.getElementById("next").style.display = "none";
}
function updateScore(){
score++;
document.getElementById("score").innerHTML = score;
}
function clearAnswer(){
document.getElementById("answr").value = " ";
}
</script>
<div id="main">
<div id="qstns"></div>
</div>
<input type="text" id="answr">Score: <label id="score"> 0 </label></input>
<button type="Sumbit" id="submit" onclick="displayNext(), checkAnswer ()">Check</button>
<button type="Submit" id="next" onclick="displayProblem(), hideNext(), clearAnswer()" style="display:none;">Next</button>
</body>
</html>
You had 2 problems; one that answer was a local variable to displayProblem() and therefore wasn't accessible by checkAnswer(), and two that you were using === instead of ==. === evaluates both type and value, userAnswer and answer are of different types so this was evaluating to false.
JS fiddle
EDIT: score will increment as expected.
<html>
<title></title>
<head>
<link rel='stylesheet' type='text/css' href='style.css'>
</head>
<body onload = 'displayProblem()'>
<script>
//'answer','score' variables should be declared outside function globally
var answer=0;
var score=0;
function displayProblem(){
//var answer = (firstNum) + (secondNum); The calculation should be after assigning value to 'firstNum', 'secondNum'
var firstNum = (Math.floor(Math.random()*10) + 1);
var secondNum = (Math.floor(Math.random()*10) + 1);
answer = (firstNum) + (secondNum);
document.getElementById('qstns').innerHTML = firstNum +' + ' + secondNum +' = ';
}
function checkAnswer(){
var userAnswer = document.getElementById('answr').value;
if(userAnswer == answer){
updateScore();
console.log('score updated');
}
else
console.log('did not update score');
}
function displayNext(){
document.getElementById('next').style.display = 'block';
}
function hideNext(){
document.getElementById('next').style.display = 'none';
}
function updateScore(){
score++;
document.getElementById('score').innerHTML = score;
}
function clearAnswer(){
document.getElementById('answr').value = ' ';
}
</script>
<div id='main'>
<div id='qstns'>
</div>
</div>
<input type='text' id='answr'>
Score: <label id='score'> 0 </label>
<button type='Sumbit' id='submit' onclick='displayNext(), checkAnswer();'>Check</button>
<button type='Submit' id='next' onclick='displayProblem(), hideNext(), clearAnswer();' style='display:none;'>Next</button>
</body>
</html>
I need to display a message on mouse click. But I also need another message to be displayed on the next mouse click. The problem is that in my code both messages appear on the first mouse click.
<!DOCTYPE>
<html>
<head>
<script>
function myfunction()
{
var obj=document.getElementById("msg1");
obj.innerHTML="message1";
if(obj.innerHTML=="message1")
{
var obj1=document.getElementById("msg2");
obj1.innerHTML="message2";
}
}
</script>
</head>
<body>
<div id="msg">
<form name="myform">
<input type="button" value="click" onclick="myfunction()">
<p id="msg1"></p>
<p id="msg2"></p>
</form>
</div>
</body>
</html>
<script>
var flag=0;
function myfunction()
{
if (flag==0)
{
var obj=document.getElementById("msg1");
obj.innerHTML="message1";
flag=1;}
else
{
var obj1=document.getElementById("msg2");
obj1.innerHTML="message2";
}
}
</script>
if (obj.innerHTML == "message1") {
var obj1 = document.getElementById("msg2");
obj1.innerHTML = "message2";
}else{
obj.innerHTML = "message1";
}
Your if would always execute because you were trying to check if obj.innerHTML == "message1" immediately after setting it to that.
Do you see that you set the innerhtml of obj to "message1" and then immediately after you check if the innerHTML is "message1" that will always be true.
You need to change the if. So it says:
if(obj.innterHTML=="message1"){
obj.innerHTML="message2";
} else {
obj.innerHTML="message1";
}
Similar to others, but what the heck:
var obj1 = document.getElementById('msg1');
var obj2 = document.getElementById('msg2');
if (obj1.innerHTML == '') {
obj1.innerHTML = 'message1';
} else {
obj2.innerHTML = 'message2';
}
function myfunction() {
var i, ele;
for(i = 1; i <= 2; i++) {
ele = document.getElementById("msg"+i);
if (ele && ele.innerHTML.length == 0) {
ele.innerHTML = 'message' + i;
return;
}
}
}
Just add a click counter to check it was first click or more then first.
<!DOCTYPE>
<html>
<head>
<script>
var $clickCount = 0;
function myfunction() {
$clickCount++;
var obj = document.getElementById("msg1");
obj.innerHTML = "message1";
if (obj.innerHTML == "message1") {
var obj1 = document.getElementById("msg2");
if ($clickCount == 2) {
obj1.innerHTML = "message2";
}
}
}
</script>
</head>
<body>
<div id="msg">
<form name="myform">
<input type="button" value="click" onclick="myfunction()">
<p id="msg1"></p>
<p id="msg2"></p>
</form>
</div>
</body>
</html>