He Guys, I tried couple of times to reset my input field with Vanilla javaScript with no success...I tried the reset() method but, perhaps I didn't add the code right...Here is my code.
<div class="container">
<h1>Enter a Number<br />
from 1 to 100.
</h1>
<input type="input" id="inputBox">
<input type="button" id="button" value="submit" onclick="myFunction()">
<span id="box1"></span>
</div>
and js
function myFunction() {
var i = document.getElementById("inputBox").value;
//for (var i = 1; i < 100; i++) {
if (i % 3 === 0 && i % 5 === 0) {
document.getElementById("box1").innerHTML = "fizzbuzz";
} else if (i % 3 === 0) {
document.getElementById("box1").innerHTML = "fizz";
} else if (i % 5 === 0) {
document.getElementById("box1").innerHTML = "buzz";
} else {
document.getElementById("box1").innerHTML = i;
}
}
I also have a pen here:
http://codepen.io/lucky500/pen/GJjVEO
Thanks!
just set the value of the input document.getElementById("inputBox").value = ""
function myFunction() {
var input = document.getElementById("inputBox");
var i = input.value;
//for (var i = 1; i < 100; i++) {
if (i % 3 === 0 && i % 5 === 0) {
document.getElementById("box1").innerHTML = "fizzbuzz";
} else if (i % 3 === 0) {
document.getElementById("box1").innerHTML = "fizz";
} else if (i % 5 === 0) {
document.getElementById("box1").innerHTML = "buzz";
} else {
document.getElementById("box1").innerHTML = i;
}
// clear input
input.value = "";
}
<div class="container">
<h1>Enter a Number<br />
from 1 to 100.
</h1>
<input type="input" id="inputBox">
<input type="button" id="button" value="submit" onclick="myFunction()">
<span id="box1"></span>
</div>
Related
I am making a dice game where you roll dice. When you roll a number that number adds to your total score. But when you roll a 1 you lose your total score and it switches to the other player. You can also hold to switch player.
As it is right now it become 0 after getting a 1 the first time. My problem is that when you switch back to the original starter player the score that was there before comes back. Like it does not stay the value of 0 but only looks like it.
var swithcing = false;
var current1 = 0;
var total1 = 0;
var current2 = 0;
var total2 = 0;
function roll() {
var randomnumber = Math.floor(Math.random() * 6) + 1;
var player1score = document.querySelector('.player1total');
var player1curent = document.querySelector('.player1');
var player2score = document.querySelector('.player2total')
var player2curent = document.querySelector('.player2')
if (randomnumber == 1) {
swithcing = !swithcing;
player1score.innerHTML = 0;
player1curent.innerHTML = 0;
player2curent.innerHTML = 0;
}
if (randomnumber == 1 && swithcing == false) {
player2score.innerHTML = 0;
}
if (swithcing == true) {
current2 += randomnumber;
player2score.innerHTML = current2;
player2curent.innerHTML = randomnumber;
}
if (swithcing == false) {
current1 += randomnumber;
player1score.innerHTML = current1;
player1curent.innerHTML = randomnumber;
}
}
function hold() {
swithcing = !swithcing;
}
<h1>Player 1</h1>
<h2 class="player1"></h2>
<h3 class="player1total"></h3>
<h1>Player 2</h1>
<h2 class="player2"></h2>
<h3 class="player2total"></h3>
<input type="button" onclick="roll()" value="Roll Dice!" />
<input type="button" onclick="hold()" value="Hold!" />
I think your code should look something like this
let switching = false;
let current1 = 0;
let total1 = 0;
let current2 = 0;
let total2 = 0;
let randomnumber = 0
const player1score = document.querySelector('.player1total');
const player1current = document.querySelector('.player1');
const player2score = document.querySelector('.player2total');
const player2current = document.querySelector('.player2');
function roll() {
randomnumber = Math.floor(Math.random() * 6) + 1;
//console.log(randomnumber);
//logic for normal rolls
if(randomnumber > 1){
if(switching==true){
current2=randomnumber;//set to number rolled
total2+=randomnumber;//sum to total score
} else {
current1=randomnumber;//set to number rolled
total1+=randomnumber;//sum to total score
}
}
//logic if player loses
if (randomnumber == 1) {
//switch
switching = !switching;
//if switches to player 2
current1=0;//reset
current2=0;//reset
if(switching==true){
//console.log("Player 2 selected");
total2+=total1//total becomes player 1 previous total
total1=0;//player 1 total resets
} else {
//console.log("Player 1 selected");
total1+=total2//total becomes player 2 previous total
total2=0;//player 2 total resets
}
}
player1score.textContent = total1;
player1current.textContent = current1;
player2current.textContent = current2;
player2score.textContent = total2;
}
function hold() {
switching = !switching;
player1score.textContent = total1;
player1current.textContent = 0;
player2current.textContent = 0;
player2score.textContent = total2;
}
<h1>Player 1</h1>
<h2 class="player1"></h2>
<h3 class="player1total"></h3>
<h1>Player 2</h1>
<h2 class="player2"></h2>
<h3 class="player2total"></h3>
<input type="button" onclick="roll()" value="Roll Dice!" />
<input type="button" onclick="hold()" value="Hold!" />
I am currently trying to learn to become a web developer and have a task where I need to use luhn algorithm to check credit cards are valid. If they are valid the box goes green, if they are not the box goes red. I’ve found the below javascript on GitHub that looks to do what I need, but I am unsure on how to add the code to make the boxes change colour. I believe I need an if/ else statement but I’m not sure how to implement it. I was thinking something like this as the code for the color change:
document.getElementById(‘cardInput’).style.backgroundColor = “green”;
Here is my html:
<form name="form1" action="#">
<ul>
<li>Name:<input id="nameInput" onkeyup="letterscheck(this)" type='text' name='name' placeholder="Enter Your Name"/></li>
<li>Email:<input id="emailInput" onkeyup="emailcheck(this)" type='text' name='email'placeholder="Enter Your Email"/></li>
<li>Card:<input id="cardInput" onkeyup="cardnumber(this)" type='text' name='card' placeholder="Enter a Proxy Credit Card Number."/></li>
<li class="submit"><input type="submit" name="submit" value="Submit" /></li>
</ul>
</form>
</div>
Here is the JS i found on GitHub:
function cardnumber(value) {
if (/[^0-9-\s]+/.test(value))
return false;
let nCheck = 0, bEven = false;
value = value.replace(/\D/g, “”);
for (var n = value.length - 1; n >= 0; n–) {
var cDigit = value.charAt(n),
nDigit = parseInt(cDigit, 10);
if (bEven && (nDigit *= 2) > 9) nDigit -= 9;
nCheck += nDigit;
bEven = !bEven;
}
return (nCheck % 10) == 0;
}
My JS for the other 2 fields
function letterscheck(inputtxt)
{
var namechecker = /^[a-zA-Z]+(?:[\s.]+[a-zA-Z]+)*$/;
if(inputtxt.value.match(namechecker))
{
document.getElementById('nameInput').style.backgroundColor = "green";
return true;
}
else
{
document.getElementById('nameInput').style.backgroundColor = "red";;
return false;
}
}
function emailcheck(inputtxt)
{
var emailchecker = /^(([^<>()[\]\\.,;:\s#"]+(\.[^<>()[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
if(inputtxt.value.match(emailchecker))
{
document.getElementById('emailInput').style.backgroundColor = "green";
return true;
}
else
{
document.getElementById('emailInput').style.backgroundColor = "red";
return false;
}
}
Hopefully, this is a really easy one for you all! Any help would be great.
Thanks!
The algorithm contains several errors so I've searched and found on Stackoverflow
You can change the background-color conditionally. I've changed the background-color inside the letterscheck for name field. You can return true or false and do it in the addEventListener like in email field.
const nameInput = document.querySelector("#nameInput")
const emailInput = document.querySelector("#emailInput")
const cardNumberInput = document.querySelector("#cardInput")
function valid_credit_card(value) {
if (/[^0-9-\s]+/.test(value)) return false;
var nCheck = 0,
nDigit = 0,
bEven = false;
value = value.replace(/\D/g, "");
for (var n = value.length - 1; n >= 0; n--) {
var cDigit = value.charAt(n),
nDigit = parseInt(cDigit, 10);
if (bEven) {
if ((nDigit *= 2) > 9) nDigit -= 9;
}
nCheck += nDigit;
bEven = !bEven;
}
return (nCheck % 10) == 0;
}
function letterscheck(inputtxt) {
var namechecker = /^[a-zA-Z]+(?:[\s.]+[a-zA-Z]+)*$/;
if (inputtxt.match(namechecker)) {
nameInput.style.backgroundColor = "green";
} else {
nameInput.style.backgroundColor = "red";;
}
}
function emailcheck(inputtxt) {
var emailchecker = /^(([^<>()[\]\\.,;:\s#"]+(\.[^<>()[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return inputtxt.match(emailchecker);
}
nameInput.addEventListener("keyup", e => {
letterscheck(e.target.value);
})
emailInput.addEventListener("keyup", e => {
const isEmailValid = emailcheck(e.target.value)
if (isEmailValid) {
e.target.style.backgroundColor = "green";
} else {
e.target.style.backgroundColor = "red";
}
})
cardNumberInput.addEventListener("keyup", e => {
const isCardValid = valid_credit_card(e.target.value);
if (isCardValid) {
cardNumberInput.style.backgroundColor = "green";
} else {
cardNumberInput.style.backgroundColor = "red";
}
})
li {
list-style-type: none;
}
input {
margin: .25rem 1rem;
}
<form name="form1" action="#">
<ul>
<li>Name:<input id="nameInput" type='text' name='name' placeholder="Enter Your Name" /></li>
<li>Email:<input id="emailInput" type='text' name='email' placeholder="Enter Your Email" /></li>
<li>Card:<input id="cardInput" type='text' name='card' placeholder="Enter a Proxy Credit Card Number." /></li>
<li class="submit"><input type="submit" name="submit" value="Submit" /></li>
</ul>
</form>
I am using next and prev buttons so one question will be shown at a time, however, once next or prev buttons are disabled, the other button doesn't work anymore either. Here's my code:
var showing = [1, 0, 0, 0];
var questions = ['q0', 'q1', 'q2', 'q3'];
function next() {
var qElems = [];
for (var i = 0; i < questions.length; i++) {
qElems.push(document.getElementById(questions[i]));
}
for (var i = 0; i <= showing.length; i++) {
if (showing[i] == 1) {
showing[i] = 0;
if (i == showing.length - 1) {
document.getElementById("next").disabled = true;
} else {
console.log(i);
qElems[i + 1].style.display = 'block';
qElems[i].style.display = 'none';
showing[i + 1] = 1;
}
break;
}
}
}
function prev() {
var qElems = [];
for (var i = 0; i < questions.length; i++) {
qElems.push(document.getElementById(questions[i]));
}
for (var i = 0; i <= showing.length; i++) {
if (showing[i] == 1) {
showing[i] = 0;
if (i == showing.length - 4) {
document.getElementById("prev").disabled = true;
} else {
qElems[i - 1].style.display = 'block';
qElems[i].style.display = 'none';
showing[i - 1] = 1;
}
break;
}
}
}
I think you want this simplified script
I had to guess the HTML, but there is only one function.
window.addEventListener("load", function() {
let showing = 0;
const questions = document.querySelectorAll(".q");
questions[showing].style.display = "block";
const next = document.getElementById("next");
const prev = document.getElementById("prev");
document.getElementById("nav").addEventListener("click", function(e) {
var but = e.target, dir;
if (but.id === "prev") dir = -1;
else if (but.id === "next") dir = 1;
else return; // not a button
questions[showing].style.display = "none"; // hide current
showing += dir; // up or down
next.disabled = showing === questions.length-1;
if (showing <= 0) showing = 0;
prev.disabled = showing === 0
questions[showing].style.display = "block";
})
})
.q { display:none }
<div class="q" id="q0">Question 0</div>
<hr/>
<div class="q" id="q1">Question 1</div>
<hr/>
<div class="q" id="q2">Question 2</div>
<hr/>
<div class="q" id="q3">Question 3</div>
<hr/>
<div id="nav">
<button type="button" id="prev" disabled>Prev</button>
<button type="button" id="next">Next</button>
</div>
Since this is a quiet interesting java script task, Im doing my own solution.
Hope this matches the requirement.
I have created 4 divs of which first one is only displayed at first. Remaining divs are placed hidden. On clicking next, the divs are displayed according to index. Once the last and first indexes are interpreted, the respective next and previous buttons are enabled and disabled.
var showing = [1, 0, 0, 0];
var questions = ['q0', 'q1', 'q2', 'q3'];
var qElems = [];
function initialize() {
for (var i = 0; i < questions.length; i++) {
qElems.push(document.getElementById(questions[i]));
}
}
function updatevisibilitystatus(showindex, hideindex) {
qElems[showindex].style.display = 'block';
qElems[hideindex].style.display = 'none';
showing[showindex] = 1;
}
function next() {
for (var i = 0; i <= showing.length; i++) {
if (showing[i] == 1) {
showing[i] = 0;
if (i == showing.length - 2) {
document.getElementById("next").disabled = true;
}
updatevisibilitystatus(i + 1, i);
document.getElementById("prev").disabled = false;
break;
}
}
}
function prev() {
for (var i = 0; i <= showing.length; i++) {
if (showing[i] == 1) {
showing[i] = 0;
if (i == 1) {
document.getElementById("prev").disabled = true;
}
updatevisibilitystatus(i - 1, i);
document.getElementById("next").disabled = false;
break;
}
}
}
<body onload="initialize()">
<div id="q0" style="display: block;">Q0</div>
<div id="q1" style="display: none;">Q1</div>
<div id="q2" style="display: none;">Q2</div>
<div id="q3" style="display: none;">Q3</div>
<button id="prev" disabled onclick="prev()">Prev</button>
<button id="next" onclick="next()">Next</button>
</body>
I'm building up a quiz app in javascript only, I want to make the final step which calculates the final score. I have 2 var : myl & score : myl = DOM.checked of my input, score = 0.
I need to make it this way:
if(myl.checked == True) {
score += 1
}
Then I'd like to print the total score in the div, but every time I try to get the total score I get only = 1 and the value of score didn't increased. Can any one help me please
I tried to set score = 0 and myl = DOM.checked and put
if(dom.checked == true) { score += 1} then DOM.innerHTML = score
function myFunction() {
var myl = document.getElementById("myCheck");
var myl1 = document.getElementById("myCheck1");
var myl2 = document.getElementById("myCheck2");
var myl3 = document.getElementById("myCheck3");
var myscore = 0;
if (myl.checked == true) {
myscore += 1;
} else if (myl1.checked == true) {
myscore += 1 ;
} else if (myl2.checked == true) {
myscore += 1;
} else if (myl3.checked == true) {
myscore += 1;
}
document.getElementById("demo").innerHTML = myscore;
}
Checkbox: <input type="checkbox" id="myCheck">
<input type="checkbox" id="myCheck1">
<input type="checkbox" id="myCheck2">
<input type="checkbox" id="myCheck3">
<button onclick="check()">Check Checkbox</button>
<button onclick="uncheck()">Uncheck Checkbox</button>
<button onclick="myFunction()">check</button>
<div id="demo"></div>
I always get 1 as result of score, not the total of correct or chosen inputs which should be 4
Because your myscore is declared inside myFunction() so it always start at 0 and plus 1 when a checkbox checked. Move it outside the function will solve it.
Or if you just want to get the amount of checked checkbox, document.querySelectorAll('input:checked').length may help.
Demo:
var myscore = 0;
function myFunction() {
var myl = document.getElementById("myCheck");
var myl1 = document.getElementById("myCheck1");
var myl2 = document.getElementById("myCheck2");
var myl3 = document.getElementById("myCheck3");
if (myl.checked == true) {
myscore += 1;
} else if (myl1.checked == true) {
myscore += 1 ;
} else if (myl2.checked == true) {
myscore += 1;
} else if (myl3.checked == true) {
myscore += 1;
}
document.getElementById("demo1").innerHTML = document.querySelectorAll('input:checked').length;
document.getElementById("demo").innerHTML = myscore;
}
Checkbox: <input type="checkbox" id="myCheck">
<input type="checkbox" id="myCheck1">
<input type="checkbox" id="myCheck2">
<input type="checkbox" id="myCheck3">
<button onclick="check()">Check Checkbox</button>
<button onclick="uncheck()">Uncheck Checkbox</button>
<button onclick="myFunction()">check</button>
<div id="demo"></div>
<div id="demo1"></div>
You need to set (var myscore = 0) outside of the function
Refactor JS portion below the way you want or build on top of it
The for loop checks to see if the checkbox is true or false - with each time adding +1. That sum is added to a variable and pushed back to the DOM.
Codepen Demo: https://codepen.io/aystarz52/pen/JQVzKz?editors=1111
HTML
Check what applies to you: <br />
<label>Are you a boy?<input type="checkbox" id="myCheck"></label><br />
<label>Are you a girl?<input type="checkbox" id="myCheck1"></label><br />
<label>Are you a car?<input type="checkbox" id="myCheck2"></label><br />
<label>Are you a dog?<input type="checkbox" id="myCheck3"></label><br />
<hr />
<label><button class="checks" onclick="checks()">Check Checkbox</button></label>
<div id="answered"></div>
<label><button class="unchecked" onclick="uncheck()">Uncheck Checkbox</button></label>
<div id="missed"></div>
<label><button class="finalscore" onclick="myFunction()">Final Score</button></label>
<div id="demo"></div>
Style
.hide {
display: none;
}
Javascript
var myscore = 0;
var missed = 0;
var answered = 0;
var myl = document.getElementById("myCheck");
var myl1 = document.getElementById("myCheck1");
var myl2 = document.getElementById("myCheck2");
var myl3 = document.getElementById("myCheck3");
var array1 = [myl, myl1, myl2, myl3];
function myFunction() {
for (i=0;i<=array1.length;i++) {
if (array1[i].checked == true) {
myscore += 1;
}
document.getElementById("demo").innerHTML = "You scored " + myscore + " Out Of 4";
document.querySelector(".finalscore").className += " hide";
}
}
function checks() {
for (i=0;i<=array1.length;i++) {
if (array1[i].checked == true) {
answered += 1;
}
document.getElementById("answered").innerHTML = "You answered " + answered + " Out Of 4";
document.querySelector(".checks").className += " hide";
}
}
function uncheck() {
for (i=0;i<=array1.length;i++) {
if (array1[i].checked == false) {
missed += 1;
}
document.getElementById("missed").innerHTML = "You missed " + missed + " Out Of 4";
document.querySelector(".unchecked").className += " hide";
}
}
okay here is the question -- .. i tried it but my js isn't working and idk where i am wrong here is the question
THE PROBLEM IS AFTER THE JS EXECUTED IT DOESN'T RUN ... LIKE IDK WHERE THE PROBLEM IS ; I KNOW IT LOADS BUT IT DOES'NT WORK
<html>
<head>
<script src="q2.js" type="text/javascript"> </script>
</head>
<div > Input 1 <input type="text" id ="input1"></div>
<div> Input 2 <input type="text" id ="input2"> </div>
<div> Result <div id="result"> </div></div>
<button onclick= "compute()">Compute</button>
</body>
</html>
the js is here
function compute(){
var n = (document.getElementById("input1").value;
var m = document.getElementById("input2").value;
var i,j;
if (Number(n)){
}
else {
alert("Error! Please put a valid Number - on input 1 ");
}
if (Number(m)){
}
else {
alert("Error! Please put a valid Number - on input 2 ");
}
for(i = 0; i < n; i++){
for(j = 0; j < m; j++){
result.innerHTML += "X";
if(j == (m-1)){
result.innerHTML += "<br />";
}
}
}
}
result.innerHTML += "X";
You forgot to set the variable result:
var result = document.getElementById("result");
And there is a loneley ( in var n = (document.getElementById("input1").value; wich will through syntax error
And you might want to clear the content of your "result"-container when calling the function again: result.innerHMLT = ''
function compute() {
var n = document.getElementById("input1").value;
var m = document.getElementById("input2").value;
var result = document.getElementById("result");
result.innerHMLT = ''
var i, j;
if (Number(n)) {} else {
alert("Error! Please put a valid Number - on input 1 ");
}
if (Number(m)) {} else {
alert("Error! Please put a valid Number - on input 2 ");
}
for (i = 0; i < n; i++) {
for (j = 0; j < m; j++) {
result.innerHTML += "X";
if (j == (m - 1)) {
result.innerHTML += "<br />";
}
}
}
}
<div>Input 1
<input type="text" id="input1">
</div>
<div>Input 2
<input type="text" id="input2">
</div>
<div>Result
<div id="result"></div>
</div>
<button onclick="compute()">Compute</button>