when adding to value a minus from value b - javascript

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>

Related

Insert Process into Queue to work Asynchronously

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>

Images not showing up in Javascript

This is supposed to be a dice game where 2 people click to roll dice and they add what they get until they reach the goal. Their score resets if they roll over 9 though. Images of dice are supposed to pop up and show what they rolled. I know the images are not on here but it still shows that there should an image there with the error symbol. I am having trouble with the second image not showing up which should come from the SetPic2 function. Any help would be appreciated. Also, the PASS buttons are supposed the pass the person's turn to the other player but the main problem is the images.
//console.log("file loaded");
//var p1Button = document.getElementById("p1");
var p1Button = document.querySelector("#p1");
var p2Button = document.querySelector("#p2");
var P1Pass = document.querySelector("P1Pass");
var P2Pass = document.querySelector("P2Pass");
var setButton = document.querySelector("#set");
var resetButton = document.querySelector("#reset");
var diceImage = document.querySelector("img");
var diceImage2 = document.querySelector("img2");
var p1Total = document.querySelector("#p1score");
var p2Total = document.querySelector("#p2score");
var targetScore = document.querySelector("#tscore");
var newScore = document.querySelector("#newtarget");
var num = 0,
num2 = 0,
p1val = 0,
p2val = 0,
target;
var playgame = true;
target = Number(targetScore.textContent); //convert the string to num
p1Button.addEventListener("click", function() {
if (playgame) {
//Math.random() --> return a value between 0 & 1
num = Math.floor((Math.random() * 6) + 1);
num2 = Math.floor((Math.random() * 6) + 1);
p1val = p1val + num + num2;
p1Total.textContent = p1val;
setButton.disabled = true;
p1Button.disabled = true;
p2Button.disabled = false;
setPic(num);
setPic2(num2);
if (num + num2 > 9) {
p1val = 0;
}
if (p1val >= target) {
playgame = false;
p1Total.classList.add("winner");
stopGame();
}
}
});
p2Button.addEventListener("click", function() {
if (playgame) {
//Math.random() --> return a value between 0 & 1
num = Math.floor((Math.random() * 6) + 1);
num2 = Math.floor((Math.random() * 6) + 1);
p2val = p2val + num + num2;
p2Total.textContent = p2val;
setButton.disabled = true;
p1Button.disabled = false;
p2Button.disabled = true;
setPic(num);
setPic2(num2);
if (num + num2 > 9) {
p2val = 0;
}
if (p2val >= target) {
playgame = false;
p2Total.classList.add("winner");
stopGame();
}
}
});
/*P1Pass.addEventListener("click", function(){
p1Button.disabled= true;
p2Button.disabled = false;
});
P2Pass.addEventListener("click", function(){
p1Button.disabled = false;
p2Button.disabled = true;
});*/
setButton.addEventListener("click", function() {
targetScore.textContent = newScore.value;
target = Number(targetScore.textContent);
setButton.disabled = true;
newScore.disabled = true;
});
resetButton.addEventListener("click", function() {
p1Button.disabled = false;
p2Button.disabled = true;
p1Total.textContent = "0";
p2Total.textContent = "0";
targetScore.textContent = "25";
setButton.disabled = false;
newScore.disabled = false;
p1Total.classList.remove("winner");
p2Total.classList.remove("winner");
playgame = true;
p1val = 0;
p2val = 0;
target = 25;
});
function stopGame() {
p1Button.disabled = true;
p2Button.disabled = true;
setButton.disabled = true;
newScore.disabled = true;
}
function setPic(val) {
if (val == 1) {
diceImage.src = "1.png";
} else if (val == 2) {
diceImage.src = "2.png";
} else if (val == 3) {
diceImage.src = "3.png";
} else if (val == 4) {
diceImage.src = "4.png";
} else if (val == 5) {
diceImage.src = "5.png";
} else if (val == 6) {
diceImage.src = "6.png";
}
}
function setPic2(val2) {
if (val2 == 1) {
diceImage2.src = "1.png";
} else if (val2 == 2) {
diceImage2.src = "2.png";
} else if (val2 == 3) {
diceImage2.src = "3.png";
} else if (val2 == 4) {
diceImage2.src = "4.png";
} else if (val2 == 5) {
diceImage2.src = "5.png";
} else if (val2 == 6) {
diceImage2.src = "6.png";
}
}
.winner {
color: green;
background-color: yellow;
}
;
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initialscale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap
.min.css" integrity="sha384-
Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<link rel="stylesheet" href="gamestyle.css">
<title>Dice Game</title>
</head>
<body>
<div class="container">
<br>
<h1> <span id="p1score">0</span> vs. <span id="p2score">0</span> </h1>
<br>
<p>Target-Score: <span id="tscore">25</span></p>
<br>
<button class="btn btn-success" id="p1"> Player One </button>
<button class="btn btn-warning" id="p2"> Player Two </button>
<br><br>
<button class="btn btn-secondary" id="P1Pass">PASS</button>
<button class="btn btn-secondary" id="P2Pass">PASS</button>
<br><br> New Target: <input type="number" id="newtarget">
<br><br>
<button class="btn btn-primary" id="set"> Set </button>
<button class="btn btn-danger" id="reset"> Reset </button>
<br><br>
<img src="">
<img src="">
</div>
<script src="gamefunction.js"></script>
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-
J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.0/dist/umd/popper.min
.js" integrity="sha384-
Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.m
in.js" integrity="sha384-
wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>
</body>
</html>
Your selector will not finding your second image element.
var diceImage2 = document.querySelector("img2");
You could give your images IDs and reference them directly:
HTML
<img id="die1" src="" />
<img id="die2" src="" />
JS
var diceImage1 = document.getElementById('die1');
var diceImage2 = document.getElementById('die2');

Basic Javascript onclick

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 show value without clicking on submit button

I am using html5 and javascript .I am reading excel file from java script and showing output..PLease analyze my code first
<input type="button" id="btnSubmit" onclick="readdata(1, 2)" value="Submit" />
var xVal = 1;
var yVal = 2
function readdata(x,y) {
x = xVal;
y = yVal;
try {
var excel = new ActiveXObject("Excel.Application");
excel.Visible = false;
var excel_file = excel.Workbooks.Open("D:\\Test.xls");// alert(excel_file.worksheets.count);
var excel_sheet = excel_file.Worksheets("Sheet1");
var data = excel_sheet.Cells(x, y).Value;
//alert(data);
drawWithexcelValue(data);
xVal = xVal + 1;
}
catch (ex) {
alert(ex);
}
Now I'm reading the file from this code and showing the output with this code:
function drawWithexcelValue(val) {
var txtSpeed = val; //alert(txtSpeed.value);
if (txtSpeed !== null) {
iTargetSpeed = txtSpeed;
// Sanity checks
if (isNaN(iTargetSpeed)) {
iTargetSpeed = 0;
} else if (iTargetSpeed < 0) {
iTargetSpeed = 0;
} else if (iTargetSpeed > 80) {
iTargetSpeed = 80;
}
job = setTimeout("draw()", 5);
}
}
Q .1 every time i click on the submit button it show me the value from excel file ,i want that i didn't have to click every time on submit button ..it automatically show the values at some time interval for say 4 seconds.
Q :-2 I didn't want the submit button ,that means when i run this code it automaticaly start running the script say onload ="readdata(1, 2)" ,but it is showing only one value ...how to show all values with some time interval ..please help!!!!!
Guys if you can give me edited code than it really will be help full for me
here this code will surely work for ya
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Speedometer HTML5 Canvas</title>
<script src="script copy.js">
</script>
</head>
<body onload='draw(0);'>
<canvas id="tutorial" width="440" height="220">
Canvas not available.
</canvas>
<div id="divHidden" style="visibility: hidden; width: 0px; height: 0px">
<form id="drawTemp">
<input type="text" id="txtSpeed" name="txtSpeed" value="20" maxlength="2" />
<input type="button" value="Draw" onclick="drawWithInputValue();">
<input type="file" id="file" onchange="checkfile(this);" />
<input type="button" id="btnSubmit" onclick="readdata(1, 2)" value="Submit" />
<button onclick="myStopFunction()">Stop Meter</button>
</form>
</div>
</body>
</html>
<script type="text/javascript" language="javascript">
var myVar=setInterval(function(){readdata(1,2)},2000);
function myStopFunction()
{
clearInterval(myVar);
}
function checkfile(sender) {
var validExts = new Array(".xlsx", ".xls", ".csv");
var fileExt = sender.value;
fileExt = fileExt.substring(fileExt.lastIndexOf('.'));
if (validExts.indexOf(fileExt) < 0) {
alert("Invalid file selected, valid files are of " +
validExts.toString() + " types.");
return false;
}
else return true;
}
var xVal = 1;
var yVal = 2
function readdata(x,y) {
x = xVal;
y = yVal;
try {
var excel = new ActiveXObject("Excel.Application");
excel.Visible = false;
var excel_file = excel.Workbooks.Open("D:\\Test.xls");// alert(excel_file.worksheets.count);
var excel_sheet = excel_file.Worksheets("Sheet1");
var data = excel_sheet.Cells(x, y).Value;
//alert(data);
drawWithexcelValue(data);
xVal = xVal + 1;
if(data==null || data=="")
{
myStopFunction();
}
excel.Application.Quit();
}
catch (ex) {
alert(ex);
}
}
</script>

events javascript

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>

Categories