I am trying to make a simple web page in which when we enter the text value in the textbox, and as soon as a user inserts a comma between the two texts, a new button gets generated. When the user presses the enter key, the buttons class should toggle between warning and danger.
I am able to achieve it so I also tried to add a delay, but the problem is all buttons class toggling takes place together and not one by one in a random manner. To create a random toggling sequence I created a random permutation of numbers for it, but since all buttons classes are toggling simultaneously I am not getting the required result.
The required result is that first for one buttons toggling should be completed and then for another button - how can I achieve this?
let element = document.querySelector('.textarea');
let cont = document.querySelector('.groupofbtns');
let lastlen = 0;
const pause = (timeoutMsec) => new Promise(resolve => setTimeout(resolve, timeoutMsec))
async function main(grp) {
// here is the delay I am trying to create between toggling but it is executing for all buttons simultaneously.
grp.classList.remove("btn-warning");
grp.classList.add("btn-danger");
await pause(3 * 1000)
grp.classList.remove("btn-danger");
grp.classList.add("btn-warning");
}
element.addEventListener("keyup", function (event) {
if (event.keyCode === 13) {
let grp = document.querySelectorAll('.btn')
let l = grp.length - 1, arr = [];
console.log(grp.length)
do {
let num = Math.floor(Math.random() * l + 1);
arr.push(num);
arr = arr.filter((item, index) => {
return arr.indexOf(item) === index
});
} while (arr.length < l);
// console.log(arr);
arr.push(0)
for (let i = 0; i <= l; i++) {
main(grp[arr[i]])
}
}
else if (event.keyCode === 8) {
let val = element.value;
//console.log(val)
let strArr = val.split(',')
let b, f;
let grp = document.querySelectorAll('.btn');
if (strArr.length > 1) {
b = strArr;
while (b[b.length - 1] == "")
b.pop()
if (b.length < strArr.length) {
cont.removeChild(grp[grp.length - 1]);
lastlen--;
}
f = b[b.length - 1];
}
if (grp.length == b.length)
grp[grp.length - 1].innerText = `${f}`;
else {
let diff = grp.length - b.length
let i = 0;
while (diff > 0) {
cont.removeChild(grp[grp.length - 1 - i]);
i++;
diff--;
lastlen--;
}
}
}
});
element.addEventListener('input', function (event) {
let val = element.value;
//console.log(val)
let strArr = val.split(',')
let b, f;
if (strArr.length > 1) {
b = strArr;
while (b[b.length - 1] == "")
b.pop()
f = b[b.length - 1];
if (event.keyCode !== 8) {
if (strArr.length > lastlen) {
let butt = document.createElement('button');
butt.classList.add('btn')
butt.classList.add('btn-warning')
//butt.classList.add('container')
butt.classList.add('active')
butt.innerText = `${f}`
cont.appendChild(butt)
lastlen = strArr.length
//cont.innerHTML += `<button type="button" class="btns" >${f}</button>`;
}//element.value = val;
else {
let b = document.querySelectorAll('.btn')
b[b.length - 1].innerText = `${f}`
}
}
}
})
.h
{
display:flex;
flex-direction: column;
width: 50%;
margin-top:30%;
align-items: center;
text-align: center;
}
.lab
{
color:white;
}
.btn
{
margin: 0.8% 0.8%;
}
.groupofbtns
{
width:50%;
margin-top: 2%;
align-items: center;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet"
integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous">
<title>Random color picker</title>
<link rel="stylesheet" href="randomcolorcss.css">
</head>
<body style="background-color: blue;">
<div class="container h">
<div class="input-group">
<label for="text" class="lab">Enter your choices here separate them with
commas, Press
Enter when you are
done</label>
<br>
<textarea cols="5" rows="5" class=" textarea form-control" placeholder="Enter Choices here" name="text"
style="width: fit-content; display: block;"></textarea>
</div>
</div>
<div class="groupofbtns container">
</div>
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"
integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj"
crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.1/dist/umd/popper.min.js"
integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN"
crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#4.5.3/dist/js/bootstrap.min.js"
integrity="sha384-w1Q4orYjBQndcko6MimVbzY0tgp4pWB4lZ7lr30WKz0vr/aWKhXdBNmNb5D92v7s"
crossorigin="anonymous"></script>
<script src="randomcolor.js"></script>
</body>
</html>
Related
Basically, I have a function that creates N input fields based on user choice, then I want to get those inputs for processing later on, though for some reason it creates a copy of the return over and over again, unless I add something like "conj.pop()" in the return. I wouldn't like to work not knowing why it only works if I pop the last one.
I put a console.log to keep track and the returned array was something like this:
Array(3)
0: 'A'
1: 'B'
2: (3) ['A','B','Array(3)]
If you expand this last array it repeats infinitely this very same description.
OBS: The inputs I've been using were simple 2,2 and A B, C D.
OBS2: The code wasn't previously in english so I translated some stuff, and left other small ones as they were variables only.
document.getElementById("ok1").onclick = () => {
const esp_qtd = document.getElementById("esp_qtd").value;
const car_qtd = document.getElementById("car_qtd").value;
document.getElementById("parte1").classList.add("invisivel");
document.getElementById("parte2").classList.remove("invisivel");
console.log(esp_qtd, car_qtd);
const generateFields = (tipo) => {
const qtd = document.getElementById(tipo + "_qtd").value;
const parent = document.getElementById(tipo + "_lista");
for (let i = 0; i < qtd; i++) {
const input = document.createElement("input");
input.setAttribute("type", "text");
input.setAttribute("id", (tipo + i));
parent.appendChild(input);
if (qtd > 5) {
if (((i + 1) % 3) == 0) parent.appendChild(document.createElement("br"));
}
console.log(i);
}
}
generateFields("esp");
generateFields("car");
const inputFields = (tipo, conj) => {
const qtd = document.getElementById(tipo + "_qtd").value;
for (let i = 0; i < qtd; i++) {
conj[i] = document.getElementById(tipo + i).value;
console.log("Iteration: " + i, conj);
}
return conj;
}
document.getElementById("ok2").onclick = () => {
const conjE = [];
const conjC = [];
conjE.push(inputFields("esp", conjE));
conjC.push(inputFields("car", conjC));
console.log(conjE);
console.log(conjC);
}
}
* {
font-family: 'Roboto', sans-serif;
font-size: 14pt;
margin-top: 1rem;
}
.invisivel {
display: none;
}
label {
margin-top: 1rem;
}
input {
margin-top: 0.5rem;
margin-right: 1rem;
margin-bottom: 0.5rem;
}
button {
margin-top: 1rem;
}
<!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>DOC</title>
<link rel="stylesheet" href="style.css">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Roboto&display=swap" rel="stylesheet">
</head>
<body>
<div class="container">
<!-- PART 1 -->
<div id="parte1">
<form>
<label>N1</label><br>
<input type="text" id="esp_qtd"><br>
<label>N2</label><br>
<input type="text" id="car_qtd"><br>
<button id="ok1" type="button">OK</button>
</form>
</div>
<!-- PART 2 -->
<div id="parte2" class="invisivel">
<div id="esp_lista">
<label>ELEMENTS 1</label><br>
</div>
<div id="car_lista">
<label>ELEMENTS 2</label><br>
</div>
<button id="ok2" type="button">OK</button>
</div>
</div>
<script src="index.js"></script>
</body>
</html>
Please change your JS as follows:
document.getElementById("ok1").onclick = () => {
const esp_qtd = document.getElementById("esp_qtd").value;
const car_qtd = document.getElementById("car_qtd").value;
document.getElementById("parte1").classList.add("invisivel");
document.getElementById("parte2").classList.remove("invisivel");
console.log(esp_qtd, car_qtd);
const generateFields = (tipo) => {
const qtd = document.getElementById(tipo + "_qtd").value;
const parent = document.getElementById(tipo + "_lista");
for (let i = 0; i < qtd; i++) {
const input = document.createElement("input");
input.setAttribute("type", "text");
input.setAttribute("id", tipo + i);
parent.appendChild(input);
if (qtd > 5) {
if ((i + 1) % 3 == 0) parent.appendChild(document.createElement("br"));
}
console.log(i);
}
};
generateFields("esp");
generateFields("car");
const inputFields = (tipo, conj) => {
const qtd = document.getElementById(tipo + "_qtd").value;
console.log("Conj:" + qtd);
for (let i = 0; i < qtd; i++) {
conj[i] = document.getElementById(tipo + i).value;
console.log("Iteration: " + i, conj);
}
return conj;
};
document.getElementById("ok2").onclick = () => {
const conjE = [];
const conjC = [];
inputFields("esp", conjE);
inputFields("car", conjC);
console.log(conjE);
console.log(conjC);
};
};
I have only removed conjE.push() and conjC.push().
Explanation:
You are passing an array to store your data in it. But you're also returning the same array and storing it in it again. This creates an infinite loop of values. Either pass the variable or return the list.
I am new to JS, I want to the code to display number of attempts made, number of guesses remaining in this simple game. I have gotten lost in the code and I don't know what I am not doing right. The const remainingAttempts returns undefined yet I want to subtract number of attempts made from maxNumberOfAttempts.
const guessInput = document.getElementById("guess");
const submitButton = document.getElementById("submit");
const resetButton = document.getElementById("reset");
const messages = document.getElementsByClassName("message");
const tooHighMessage = document.getElementById("too-high");
const tooLowMessage = document.getElementById("too-low");
const maxGuessesMessage = document.getElementById("max-guesses");
const numberOfGuessesMessage = document.getElementById("number-of-guesses");
const correctMessage = document.getElementById("correct");
let targetNumber;
let attempts = 0;
let maxNumberOfAttempts = 5;
// Returns a random number from min (inclusive) to max (exclusive)
// Usage:
// > getRandomNumber(1, 50)
// <- 32
// > getRandomNumber(1, 50)
// <- 11
function getRandomNumber(min, max) {
return Math.floor(Math.random() * (max - min)) + min;
}
function checkGuess() {
// Get value from guess input element
const guess = parseInt(guessInput.value, 10);
attempts = attempts + 1;
hideAllMessages();
if (guess === targetNumber) {
numberOfGuessesMessage.style.display = "";
numberOfGuessesMessage.innerHTML = `You made ${attempts} guesses`;
correctMessage.style.display = "";
submitButton.disabled = true;
guessInput.disabled = true;
}
if (guess !== targetNumber) {
if (guess < targetNumber) {
tooLowMessage.style.display = "";
} else {
tooHighMessage.style.display = ""; //replaced else condition statement
}
const remainingAttempts = maxNumberOfAttempts - attempts;
numberOfGuessesMessage.style.display = "";
numberOfGuessesMessage.innerHTML = `You guessed ${guess}. <br> ${remainingAttempts} guesses remaining`;
}
if (attempts === maxNumberOfAttempts) {
maxGuessesMessage.style.display = "";
submitButton.disabled = true;
guessInput.disabled = true;
}
guessInput.value = "";
resetButton.style.display = "";
}
function hideAllMessages() {
/*replaced elementIndex <= messages.length to elementIndex < messages.length*/
for (let elementIndex = 0; elementIndex < messages.length; elementIndex++) {
messages[elementIndex].style.display = "none"; //removed [elementIndex]
}
// for (let message in messages.value) {
// //used for..in to iterate through the HTML collection
// message.style.display = "none";
// }
}
function setup() {
// Get random number
targetNumber = getRandomNumber(1, 100);
console.log(`target number: ${targetNumber}`);
// Reset number of attempts
maxNumberOfAttempts = 0;
// Enable the input and submit button
submitButton.disabled = false;
guessInput.disabled = false;
hideAllMessages();
resetButton.style.display = "none";
}
submitButton.addEventListener("click", checkGuess);
resetButton.addEventListener("click", setup);
setup();
main {
display: flex;
justify-content: center;
flex-direction: column;
align-items: center;
margin: auto;
}
#guess {
width: 5em;
}
#reset {
margin: 20px;
}
<!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" />
<link href="guess.css" rel="stylesheet" />
<title>Number Guesser</title>
</head>
<body>
<main>
<h1>Guessing Game</h1>
<p>
I'm thinking of a number from 1 to 99! Can you guess it in 5 tries or
less?
</p>
<div>
<input type="number" id="guess" min="1" max="99" />
<button id="submit">Submit Guess</button>
</div>
<div>
<p class="message" id="number-of-guesses"></p>
<p class="message" id="too-high">You guessed too high. Try again.</p>
<p class="message" id="too-low">You guessed too low. Try again.</p>
<p class="message" id="max-guesses">
You reached the max number of guesses
</p>
<p class="message" id="correct">
Congratulations, You guessed correctly! <br />
Would you like to play again?
</p>
</div>
<button id="reset">Reset</button>
</main>
<script src="guess.js"></script>
</body>
</html
just increment attempts as attempts++; below const remainingAttempts = maxNumberOfAttempts - attempts;. this should solve the no. of attempts part.
In setup(), when you reset the number of attempts, you should be setting it to 5: maxNumberOfAttempts = 5;
Additionally, in checkGuess(), you should:
Make sure to decrease the number of attempts with each guess. Add maxNumberOfAttempts-- at the top of the function.
At the bottom of if (guess !== targetNumber), you can replace the variable in the message from ${remainingAttempts} to ${maxNumberOfAttempts}
, since maxNumberOfAttempts is now keeping track of the amount of attempts remaining.
Lastly, the next if statement can check if the user is out of attempts with if (maxNumberOfAttempts === 0) {...}
This eliminates the need to use 3 different 'attempt' variables since you're resetting back to '5' at each instance of setup() anyway.
I am trying to do an assignment where it makes random lotto numbers. I have it all built out, but when I put the first value in and it runs it will post to the HTML. Then doing a second value will concatenate to the first instead of clearing. I've tried .reset and value = "" but I must be doing something wrong. I tried searching the old posts, but couldn't find anything as I wasn't sure exactly what the problem was.
var buttons = document.getElementById("create");
var numbers = [];
var shownSelection = ""
function makeIt() {
var input = document.getElementById("count").value;
var resultsDiv = document.getElementById("results");
if (input > 8) {
alert("Too many numbers. Please try less than 8.")
} else if (input < 1)
alert("Nothing to predict.")
else
for (var i = 0; i < input; i++) {
numbers[i] = Math.ceil(Math.random() * 99);
}
for (var i = 0; i < input; i++) {
if (i == input - 1) {
shownSelection = shownSelection + numbers[i];
} else {
shownSelection = shownSelection + numbers[i] + "-";
}
}
resultsDiv.innerHTML =
shownSelection;
document.getElementById("results").value = "";
};
<!DOCTYPE html>
<html lang="en">
<head>
<title>Lucky Lotto Game</title>
<link href="css/style.css" rel="stylesheet" type="text/css">
<script src="js/javascript.js" defer></script>
</head>
<body>
<div class="entry">
<ul>
<li><input type="text" id="count" placeholder="Enter number between 1 and 8" /></li>
</ul>
</div>
<div id="buttons" class="buttons">
<button id="create" onclick="makeIt()" class="create">Get my numbers</button>
</div><br><br><br>
<span id="results"></span>
</body>
</html>
You should initialize your 'shownSelection' variable inside the function so it will be empty each time you press the button:
var buttons = document.getElementById("create");
var numbers = [];
function makeIt() {
var shownSelection = ""
var input = document.getElementById("count").value;
var resultsDiv = document.getElementById("results");
if (input > 8) {
alert("Too many numbers. Please try less than 8.")
} else if (input < 1)
alert("Nothing to predict.")
else
for (var i = 0; i < input; i++) {
numbers[i] = Math.ceil(Math.random() * 99);
}
for (var i = 0; i < input; i++) {
if (i == input - 1) {
shownSelection = shownSelection + numbers[i];
} else {
shownSelection = shownSelection + numbers[i] + "-";
}
}
resultsDiv.innerHTML =
shownSelection;
document.getElementById("results").value = "";
};
<!DOCTYPE html>
<html lang="en">
<head>
<title>Lucky Lotto Game</title>
<link href="css/style.css" rel="stylesheet" type="text/css">
<script src="js/javascript.js" defer></script>
</head>
<body>
<div class="entry">
<ul>
<li><input type="text" id="count" placeholder="Enter number between 1 and 8" /></li>
</ul>
</div>
<div id="buttons" class="buttons">
<button id="create" onclick="makeIt()" class="create">Get my numbers</button>
</div><br><br><br>
<span id="results"></span>
</body>
</html>
I was excited because my prime number program was working, but when I tried certain numbers like 5 and 10, 2 and 11, it wasn't working. I have tried to figure it out myself, and by looking at other things related to what I was doing, but I couldn't figure it out. I would appreciate an answer and thank everyone who helps, because I am just a beginner at coding and want to learn more.
var minimum;
var maximum;
var primes;
function myFunction(e) {
e.preventDefault();
minimum = document.getElementById('Minimum').value;
maximum = document.getElementById('Maximum').value;
primes = [];
listOfPrimes(minimum, maximum);
primes = primes.filter(function(x) {
return x > 1;
});
primes = primes.toString();
primes = primes.replace(/,(?=[^\s])/g, ", ");
document.getElementById("Your_Primes").innerHTML = primes;
}
function isPrime(num) {
for (var i = 2; i <= num / 2; i++)
if (num % i === 0) {
return false;
}
primes.push(num);
}
function listOfPrimes(min, max) {
for (var j = min; j <= max; j++) {
isPrime(j);
}
}
body {
background-color: #dbdbdb;
}
#prime-checker {
background-color: #89a9dd;
margin: 5px;
padding: 5px;
text-align: center;
}
.the-primes {
background-color: #587cb7;
padding: 15px;
margin: 10px;
}
<!doctype html>
<html>
<head>
<title>Prime Lister</title>
<link href="main.css" rel="stylesheet" type="text/css">
</head>
<body>
<div id="prime-checker">
<form>
<h2>Minimum Number:</h2><br>
<input type="number" placeholder="MinimumWholeNumber" id="Minimum" multiple="1" min="0" required><br><br>
<h2>Maximum Number:</h2><br>
<input type="number" placeholder="MaximumWholeNumber" id="Maximum" multiple="1" min="0" required><br><br><br>
<button id="button" onclick="myFunction(event)">Enter</button>
</form>
<div class="the-primes"><h2>Your Primes:</h2>
<p id="Your_Primes"></p>
</div>
</div>
<script type="text/javascript" src="Web_Prime_Lister.js"></script>
</body>
</html>
Your code for calculating a prime looks fine. The problem is that you are using the raw strings from the minimum and maximum to create your range. The problem is that strings are compared lexigraphically, so:
"2" < "100" // false
So when you pass those values into your function listOfPrimes, that loop will terminate early due to the string comparison.
To fix it, just convert your input values to numbers before you use them:
minimum = Number(document.getElementById('Minimum').value);
maximum = Number(document.getElementById('Maximum').value);
Here's your snippet with that fix, everything looks like it's working well:
var minimum;
var maximum;
var primes;
function myFunction(e) {
e.preventDefault();
minimum = Number(document.getElementById('Minimum').value);
maximum = Number(document.getElementById('Maximum').value);
primes = [];
listOfPrimes(minimum, maximum);
primes = primes.filter(function(x) {
return x > 1;
});
primes = primes.toString();
primes = primes.replace(/,(?=[^\s])/g, ", ");
document.getElementById("Your_Primes").innerHTML = primes;
}
function isPrime(num) {
for (var i = 2; i <= num / 2; i++)
if (num % i === 0) {
return false;
}
primes.push(num);
}
function listOfPrimes(min, max) {
for (var j = min; j <= max; j++) {
isPrime(j);
}
}
body {
background-color: #dbdbdb;
}
#prime-checker {
background-color: #89a9dd;
margin: 5px;
padding: 5px;
text-align: center;
}
.the-primes {
background-color: #587cb7;
padding: 15px;
margin: 10px;
}
<!doctype html>
<html>
<head>
<title>Prime Lister</title>
<link href="main.css" rel="stylesheet" type="text/css">
</head>
<body>
<div id="prime-checker">
<form>
<h2>Minimum Number:</h2><br>
<input type="number" placeholder="MinimumWholeNumber" id="Minimum" multiple="1" min="0" required><br><br>
<h2>Maximum Number:</h2><br>
<input type="number" placeholder="MaximumWholeNumber" id="Maximum" multiple="1" min="0" required><br><br><br>
<button id="button" onclick="myFunction(event)">Enter</button>
</form>
<div class="the-primes"><h2>Your Primes:</h2>
<p id="Your_Primes"></p>
</div>
</div>
<script type="text/javascript" src="Web_Prime_Lister.js"></script>
</body>
</html>
PS: You can further optimize your isPrime function by only checking divisors up to Math.floor(Math.sqrt(num)). That will save you many many iterations, especially for a large number. So:
function isPrime(num) {
var max = Math.floor(Math.sqrt(num));
for (var i = 2; i <= max; i++)
if (num % i === 0) {
return false;
}
primes.push(num);
}
As you can see, for a 10-digit prime, the running time is very much reduced:
function isPrimeSqrt(num) {
var max = Math.floor(Math.sqrt(num));
for (var i = 2; i <= max; i++)
if (num % i === 0) {
return false;
}
return true;
}
function isPrimeHalf(num) {
var max = Math.floor(num / 2);
for (var i = 2; i <= max; i++)
if (num % i === 0) {
return false;
}
return true;
}
let now = Date.now();
const pHalf = isPrimeHalf(1010189899);
console.log("Using 'Half' took:", Date.now() - now, "ms. Is prime:", pHalf);
now = Date.now()
const pSqrt = isPrimeSqrt(1010189899);
console.log("Using 'Sqrt' took:", Date.now() - now, "ms. Is prime:", pSqrt);
Got it!
Simply change this line:
for (var j = min; j <= max; j++) {
to this:
for (var j = parseInt(min); j <= parseInt(max); j++) {
Get familiar with Debugger Tools (F12 in most browsers). There you can pause execution in certain lines and check value and type of variables. If you do it, there you'll see than min = "5", insted of min = 5. That's why 5-49 doesn't work, beacuse "5" is smaller than "49" (beacuse it's first digit is lower), so it doesn't loop at all.
I want to add a variable b, that starts off at a value of 100. When I click the add button for value a, it adds 1 to value a but minus 1 from the 100 and vice versa with the minus button.
<head>
<script type="text/javascript">
var b = 100
document.getElementById('Valueb').innerHTML = b;
var a = 0;
var add = function(valueToAdd){
a += valueToAdd;
document.getElementById('Valuea').innerHTML = a;
if(a == 0) {
document.getElementById('minus').disabled = true;
} else {
document.getElementById('minus').disabled = false;
}
}
</script>
</head>
<body>
Valueb:<span id="Valueb">0</span>
Valuea:<span id="Valuea">0</span>
<button type="button" id = add onclick="javascript:add(1)">+</button>
<button type="button" id = minus onclick="javascript:add(-1)">-</button>
</body>
You need to put the script in the end of body section.
<head>
<body>
Value b:<span id="Valueb">0</span>
Value a:<span id="Valuea">0</span>
<button type="button" id = add onclick="javascript:add(1)">+</button>
<button type="button" id = minus onclick="javascript:add(-1)">-</button>
<script type="text/javascript">
var b = 100
document.getElementById('Valueb').innerHTML = b;
var a = 0;
var add = function(valueToAdd){
a += valueToAdd;
b -=valueToAdd;
document.getElementById('Valuea').innerHTML = a;
document.getElementById('Valueb').innerHTML = b;
if(a == 0) {
document.getElementById('minus').disabled = true;
} else {
document.getElementById('minus').disabled = false;
}
}
</script>
</head>
</body>
Press F12 (or whatever) in your browser and look in the console.
Reload the page and you can see errors in your Javascript code.
<span id="Valueb">0</span> if not visible to Javascript the way your code is.
So you can put the Javascript at the end before </body> or you can use window.addEventListener('load', functionname, false); so the code will run when the page has loaded.
Maybe this is what your looking for...
<!DOCTYPE html>
<head>
<title>Something</title>
<style type="text/css">
body, button {
margin: 20px;
font-size: 80px;
text-align: center;
}
button {
width: 2em;
height: 2em;
}
</style>
<script type="text/javascript">
'use strict';
var a = 0,
b = 100,
outputa = null,
outputb = null,
buttonadd = null,
buttonminus = null;
function letsgo() {
outputa = document.getElementById('Valuea');
outputb = document.getElementById('Valueb');
buttonadd = document.getElementById('add');
buttonminus = document.getElementById('minus');
outputa.innerHTML = a;
outputb.innerHTML = b;
checkdisable();
}
function add(valueToAdd) {
a += valueToAdd;
b -= valueToAdd;
outputa.innerHTML = a;
outputb.innerHTML = b;
checkdisable();
}
function checkdisable() {
if(a <= 0) {
buttonminus.disabled = true;
} else {
buttonminus.disabled = false;
}
if(a >= 100) {
buttonadd.disabled = true;
} else {
buttonadd.disabled = false;
}
}
if (window.addEventListener) {
window.addEventListener("load", letsgo, false);
}
</script>
</head>
<body>
<div>
Valuea:<span id="Valuea">X</span>
Valueb:<span id="Valueb">X</span>
</div>
<div>
<button type="button" id="add" onclick="javascript:add(1)">+</button>
<button type="button" id="minus" onclick="javascript:add(-1)">-</button>
</div>
</body>