How do I display results? - javascript

I am new to HTML and Javascript. I am trying to make a simple website that counts up yes and no votes. I want to display the number of votes for each. The results should be updated after each vote. When I enter a vote, it gets updated for a split second then reverts back to 0,0,0. How do I resolve this?
var yes = 0;
var no = 0;
function clickYes() {
yes++;
alert("You pressed yes");
refreshResults();
}
function clickNo() {
no++;
alert("You pressed no");
refreshResults();
}
function refreshResults() {
var results = document.getElementById('results');
results.innerHTML = "Total: " + (yes + no);
results.innerHTML += "<br>Yes: " + yes;
results.innerHTML += "<br>No: " + no;
}
<!DOCTYPE html>
<html>
<script src="voteCount.js" type="text/javascript"></script>
<head>
<h1>This Website Counts Up Votes</h1>
</head>
<body>
<div id="userInput">
<h2>Yes or No?</h2>
<form>
<button type="radio" onclick="clickYes()" id="yesbutton">Yes</button>
<button type="radio" onclick="clickNo()" id="nobutton">No</button>
</form>
</div>
<h3 id="results">
<script>
refreshResults();
</script>
</h3>
</html>

Hi Try to remove script tag from your html file.
its working fine for me.
Hope this helps...
var yes = 0;
var no = 0;
function clickYes() {
yes++;
refreshResults();
}
function clickNo() {
no++;
refreshResults();
}
function refreshResults() {
var results = document.getElementById('results');
results.innerHTML = "Total: " + (yes + no);
results.innerHTML += "<br>Yes: " + yes;
results.innerHTML += "<br>No: " + no;
}
<!DOCTYPE html>
<html>
<script src="voteCount.js" type="text/javascript"></script>
<head>
<h1>This Website Counts Up Votes</h1>
</head>
<body>
<div id="userInput">
<h2>Yes or No?</h2>
<form>
<button type="radio" onclick="clickYes()" id="yesbutton">Yes</button>
<button type="radio" onclick="clickNo()" id="nobutton">No</button>
</form>
</div>
<h3 id="results">
</html>

The main problem is button is reloading the page. Either give type="button" or you need to prevent the default event. Also there are few issues:
You haven't closed the </body>.
You cannot have <h1> inside <head>!
Button's type should be either of button, submit or reset, which defaults to submit.
You cannot have a <script> tag, that way how you have used it.
Working Snippet with the alert.
var yes = 0;
var no = 0;
function clickYes() {
yes++;
alert("You pressed yes");
refreshResults();
}
function clickNo() {
no++;
alert("You pressed no");
refreshResults();
}
function refreshResults() {
var results = document.getElementById('results');
results.innerHTML = "Total: " + (yes + no);
results.innerHTML += "<br>Yes: " + yes;
results.innerHTML += "<br>No: " + no;
}
<h1>This Website Counts Up Votes</h1>
<div id="userInput">
<h2>Yes or No?</h2>
<form>
<button type="button" onclick="clickYes()" id="yesbutton">Yes</button>
<button type="button" onclick="clickNo()" id="nobutton">No</button>
</form>
</div>
<h3 id="results"></h3>

try this
function refreshResults() {
var results = document.getElementById('results');
var output = "Total: " + (yes + no);
output += "<br>Yes: " + yes;
output += "<br>No: " + no;
results.innerHTML = output;
}

Related

How to change the font color of variable after show result in JavaScript?

I'm a beginner in JavaScript and I'm trying to change the color of variable/element (name, age, and status) when it show the output in my JavaScript coding. For some reason the output not appear. Here is the code below:
<html>
<head>
<script>
function ageCalculator() {
var name = document.getElementById("name").value;
var birthdate = document.getElementById("dob").value;
var dob = new Date(birthdate);
var status;
if(birthdate==null || birthdate=='') {
document.getElementById("message").innerHTML = "<br><br>Choose a date properly!";
return false;
} else {
var month_diff = Date.now() - dob.getTime();
var age_date = new Date(month_diff);
var year = age_date.getUTCFullYear();
var age = Math.abs(year - 1970);
if (age<20)
status = "You are still young!";
else if (age>=20 && age<=25)
status = "Now start thinking to have your own family!";
else
status = "Be responsible and care about others!";
return document.getElementById("result").innerHTML =
" Hello " + name.css('color','red') + "<br><br> You are " + age.css('color','red') + " year-old" + "<br><br>" + status.css('color','red');
}
}
</script>
</head>
<body>
<center>
<b> Enter your name : <input type="text" id="name" name="name" ><br><br>
<b> Enter your birthday: <input type=date id = dob> </b>
<span id = "message" style="color:darkred"> </span> <br><br>
<button type="submit" onclick = "ageCalculator()"> Submit </button> <br>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h4 id="result" align="center"></h4>
</center>
</body>
</html>
Here is the sample of the output:
enter image description here
You can add a CSS class in style tag and add a span tag around the text where you want to apply the style.
Add below style tag in your head element.
<style>
.txtColor {
color: red;
}
</style>
Now, in the innerHTML, add the span tag and apply the styles.
return document.getElementById("result").innerHTML =
" Hello <span class='txtColor'>" + name + "</span><br><br> You are <span class='txtColor'>" + age + "</span> year-old" + "<br><br><span class='txtColor'>" + status + "</span>";
Please mark this as an answer if it helps.

Computer Guess A Number JavaScript

I am trying to create a simple "guess the number game" in a web page where a user is the one thinking of the number and the computer is to guess the number(in range 1-100) that the user is thinking (no user input required). I've created four buttons for user to respond to the computer's guess: Start, Guess Higher, Guess Lower, Bingo. I have a problems with this range. If user click button 'Lover' it should became the biggest number (For example, 60 is too high, then computer guess between 1-60)(same with 'Higher'), but can't connect it together. Here is my code:
let computerGuess = 0,
numberOfGuesses = 0;
function writeMessage(elementId, message, appendMessage) {
let elemToUpdate = document.getElementById(elementId);
if (appendMessage) {
elemToUpdate.innerHTML = elemToUpdate.innerHTML + message;
} else {
elemToUpdate.innerHTML = message;
}
};
function newGame() {
computerGuess = 0;
numberOfGuesses = 1;
writeMessage('historyList', '');
document.getElementById('buttonLover').disabled = true;
document.getElementById('buttonHigher').disabled = true;
document.getElementById('buttonBingo').disabled = true;
}
function randomNumber(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min)) + min;
}
function computerGuessed() {
let compGuess = document.getElementById('compGuess'),
butLover = document.getElementById('buttonLover'),
butHigher = document.getElementById('buttonHigher'),
butBingo = document.getElementById('buttonBingo'),
statusArea = document.getElementById('statusArea'),
historyList = document.getElementById('historyList');
document.getElementById('buttonArea').disabled = true;
butLover.disabled = false;
butHigher.disabled = false;
butBingo.disabled = false;
let a = 1, b = 100;
computerGuess = randomNumber(a, b);
writeMessage('compGuess', '<p>' + computerGuess + '</p>', true);
writeMessage('statusArea', '<p>Choose a number between 1-100 and click the button.</p>');
butLover.addEventListener("click", function () {
writeMessage('historyList', '<li>' + computerGuess + ' (too high)</li>', true);
writeMessage('compGuess', '<p>' + '' + '</p>', false);
computerGuess = randomNumber(a, computerGuess);
writeMessage('compGuess', '<p>' + computerGuess + '</p>', true);
numberOfGuesses++;
});
butHigher.addEventListener("click", function () {
writeMessage('historyList', '<li>' + computerGuess + ' (too low)</li>', true);
writeMessage('compGuess', '<p>' + '' + '</p>', false);
computerGuess = randomNumber(computerGuess, b);
writeMessage('compGuess', '<p>' + computerGuess + '</p>', true);
numberOfGuesses++;
});
butBingo.addEventListener("click", function () {
writeMessage('statusArea', '<p>You got me in ' + numberOfGuesses + ' guesses, I was thinking ' + computerGuess + '. Let\'s go again...</p>');
writeMessage('compGuess', '<p>' + '' + '</p>', false);
document.getElementById('buttonArea').disabled = false;
newGame();
});
}
window.onload = function () {
newGame();
document.getElementById('buttonArea').addEventListener('click', computerGuessed);
};
<div id="game">
<h1>Computer Guessing Game</h1>
<div id="statusArea">
<p>Choose a number between 1-100 and click the button.</p>
</div>
<div id="compGuess">
</div>
<div class="buttons">
<input type="button" value="Start" class="button" id="buttonArea"/>
<input type="button" value="Lover" class="button" id="buttonLover"/>
<input type="button" value="Higher" class="button" id="buttonHigher"/>
<input type="button" value="Bingo" class="button" id="buttonBingo"/>
</div>
<div id="historyArea">
<h2>Computer Previous Guesses</h2>
<ol id="historyList">
</ol>
</div>
</div>
Each time you call computerGuessed() you reset a & b to 1 and 100. Try setting them as global vars (since you're already using global vars), and set them to 1 and 100 on the start of each game.
let computerGuess = 0,
numberOfGuesses = 0,
a=0,
b=100;
function writeMessage(elementId, message, appendMessage) {
let elemToUpdate = document.getElementById(elementId);
if (appendMessage) {
elemToUpdate.innerHTML = elemToUpdate.innerHTML + message;
} else {
elemToUpdate.innerHTML = message;
}
};
function newGame() {
computerGuess = 0;
numberOfGuesses = 1;
a = 0;
b = 100;
writeMessage('historyList', '');
document.getElementById('buttonLower').disabled = true;
document.getElementById('buttonHigher').disabled = true;
document.getElementById('buttonBingo').disabled = true;
}
function randomNumber(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min)) + min;
}
function computerGuessed() {
let compGuess = document.getElementById('compGuess'),
butLower = document.getElementById('buttonLower'),
butHigher = document.getElementById('buttonHigher'),
butBingo = document.getElementById('buttonBingo'),
statusArea = document.getElementById('statusArea'),
historyList = document.getElementById('historyList');
document.getElementById('buttonArea').disabled = true;
butLower.disabled = false;
butHigher.disabled = false;
butBingo.disabled = false;
computerGuess = randomNumber(a, b);
writeMessage('compGuess', '<p>' + computerGuess + '</p>', true);
writeMessage('statusArea', '<p>Choose a number between 1-100 and click the button.</p>');
}
window.onload = function () {
newGame();
document.getElementById('buttonArea').addEventListener('click', computerGuessed);
let butLower = document.getElementById('buttonLower'),
butHigher = document.getElementById('buttonHigher'),
butBingo = document.getElementById('buttonBingo');
butLower.addEventListener("click", function () {
writeMessage('historyList', '<li>' + computerGuess + ' (too high)</li>', true);
writeMessage('compGuess', '<p>' + '' + '</p>', false);
b = computerGuess;
computerGuessed();
writeMessage('compGuess', '<p>' + computerGuess + '</p>', true);
numberOfGuesses++;
});
butHigher.addEventListener("click", function () {
writeMessage('historyList', '<li>' + computerGuess + ' (too low)</li>', true);
writeMessage('compGuess', '<p>' + '' + '</p>', false);
a = computerGuess;
computerGuessed();
writeMessage('compGuess', '<p>' + computerGuess + '</p>', true);
numberOfGuesses++;
});
butBingo.addEventListener("click", function () {
writeMessage('statusArea', '<p>You got me in ' + numberOfGuesses + ' guesses, I was thinking ' + computerGuess + '. Let\'s go again...</p>');
writeMessage('compGuess', '<p>' + '' + '</p>', false);
document.getElementById('buttonArea').disabled = false;
newGame();
});
};
<div id="game">
<h1>Computer Guessing Game</h1>
<div id="statusArea">
<p>Choose a number between 1-100 and click the button.</p>
</div>
<div id="compGuess">
</div>
<div class="buttons">
<input type="button" value="Start" class="button" id="buttonArea"/>
<input type="button" value="Lower" class="button" id="buttonLower"/>
<input type="button" value="Higher" class="button" id="buttonHigher"/>
<input type="button" value="Bingo" class="button" id="buttonBingo"/>
</div>
<div id="historyArea">
<h2>Computer Previous Guesses</h2>
<ol id="historyList">
</ol>
</div>
</div>
This version disables lower/higher buttons if we've already ruled out those possibilities, and it detects bingo automatically if there is no other option left.
//initialize global variables to keep track of stuff between functions
var min = 1;
var max = 100;
var currentGuess = -1;
function start() {
//reset everything
min = 1;
max = 100;
document.getElementById("historyList").innerHTML = "";
disable("startButton");
enable("lowerButton");
enable("higherButton");
enable("bingoButton");
//and guess
guess();
}
function guess() {
//generate a guess between min and max
currentGuess = rando(min, max);
//disable higher/lower buttons if we've ruled out those possibilities
currentGuess == min ? disable("lowerButton") : enable("lowerButton");
currentGuess == max ? disable("higherButton") : enable("higherButton");
//tell the user the guess
document.getElementById("compGuess").innerHTML = currentGuess;
}
function lower() {
//our guess was too high, so our new max is one lower than that guess
max = currentGuess - 1;
//automatically detect bingo if it's the only possible outcome left and don't bother executing the rest of the lower function
if (max == min) {
currentGuess = min;
return bingo();
}
//record that the guess was too high
document.getElementById("historyList").innerHTML += "<li>" + currentGuess + " (too high)</li>";
guess();
}
function higher() {
//our guess was too low, so our new min is one higher than that guess
min = currentGuess + 1;
//automatically detect bingo if it's the only possible outcome left and don't bother executing the rest of the higher function
if (max == min) {
currentGuess = min;
return bingo();
}
//record that the guess was too low
document.getElementById("historyList").innerHTML += "<li>" + currentGuess + " (too low)</li>";
guess();
}
function bingo() {
//record that the guess was a bingo
document.getElementById("historyList").innerHTML += "<li>" + currentGuess + " (BINGO)</li>";
//only allow start button
enable("startButton");
disable("lowerButton");
disable("higherButton");
disable("bingoButton");
//give the user a breakdown
document.getElementById("compGuess").innerHTML = "You got me in " + document.getElementsByTagName("li").length + " guesses. I was thinking " + currentGuess + ". Let's go again...";
}
//these two functions just make our code easier to read
function disable(id) {
document.getElementById(id).disabled = true;
}
function enable(id) {
document.getElementById(id).disabled = false;
}
<script src="https://randojs.com/1.0.0.js"></script>
<div id="game">
<h1>Computer Guessing Game</h1>
<div id="statusArea">
<p>Choose a number between 1-100 and click the button.</p>
</div>
<div id="compGuess"></div>
<div class="buttons">
<input type="button" value="Start" id="startButton" onclick="start();" />
<input type="button" value="Lower" id="lowerButton" onclick="lower();" disabled/>
<input type="button" value="Higher" id="higherButton" onclick="higher();" disabled/>
<input type="button" value="Bingo" id="bingoButton" onclick="bingo();" disabled/>
</div>
<div id="historyArea">
<h2>Computer Previous Guesses</h2>
<ol id="historyList"></ol>
</div>
</div>
It uses randojs.com to make the randomness easier to read, so if you use this code, make sure you have this in the head tag of your html document:
<script src="https://randojs.com/1.0.0.js"></script>
try the following ...
start.html
<!DOCTYPE html>
<html>
<head>
<script>
function StartGame()
{
aMaxValue = Number(theMaxValueText.value);
window.localStorage.setItem ("theMaxValueToGuess", aMaxValue);
aNumberToGuess = Math.floor ( Math.random() * aMaxValue + 1 );
window.localStorage.setItem ("theNumberToGuess", aNumberToGuess);
aMaxNumberOfTries = Math.floor ( Math.log2 (aMaxValue) + 1 );
window.localStorage.setItem ("theMaxNumberOfTries", aMaxNumberOfTries);
window.localStorage.setItem ("theUserTriesCount", 0);
aPrevGuessesString = "";
window.localStorage.setItem ("thePrevGuessesString", aPrevGuessesString);
document.location.href = "play.html";
}
</script>
</head>
<body>
<h1>Guess a Number</h1>
<div class="form">
<label for="theMaxValueText">Max Value to Guess:</label>
<input type="text" id="theMaxValueText">
<input type="submit" value="Play" id="ExecPlayBtn" onclick="StartGame()">
</div>
</body>
</html>
play.html
<!DOCTYPE html>
<html>
<head>
<script>
var theMaxNumberToGuess = Number ( window.localStorage.getItem ("theMaxValueToGuess") );
// let theMaxNumberOfTries = 0;
// let theNumberToGuess = 0;
// let theUserTriesCount = 0;
function getMaxNumberOfTries() {
return Number ( window.localStorage.getItem ("theMaxNumberOfTries") );
}
function getNumberToGuess() {
return Number ( window.localStorage.getItem ("theNumberToGuess") );
}
function getUserTriesCount() {
return Number ( window.localStorage.getItem ("theUserTriesCount") );
}
function incrUserTriesCount()
{
aUserTriesCount = getUserTriesCount();
++ aUserTriesCount;
window.localStorage.setItem ("theUserTriesCount", aUserTriesCount);
}
function getNumberOfTriesLeft()
{
aMaxNumberOfTries = getMaxNumberOfTries();
aUserTriesCount = getUserTriesCount();
aNumberOfTriesLeft = aMaxNumberOfTries - aUserTriesCount;
return aNumberOfTriesLeft;
}
function getPrevGuessesString() { return window.localStorage.getItem ("thePrevGuessesString"); }
function addToPrevGuessesString (aStr)
{
aPrevGuessesString = getPrevGuessesString();
aPrevGuessesString += (aStr + " ");
window.localStorage.setItem ("thePrevGuessesString", aPrevGuessesString);
}
function PageLoaded()
{
document.getElementById("theMaxNumberToGuessLabel").innerHTML = theMaxNumberToGuess;
// compute values ...
// theNumberToGuess = Math.floor ( Math.random() * theMaxNumberToGuess + 1 );
// theMaxNumberOfTries = Math.floor ( Math.log2 (theMaxNumberToGuess) + 1 );
// theUserTriesCount = 0;
DisplayGameStatus();
}
window.addEventListener ("load", PageLoaded);
function DisplayNumberOfTriesLeft()
{
aNumberOfTriesLeft = getNumberOfTriesLeft();
document.getElementById("theTriesLeftCountLabel").innerHTML = aNumberOfTriesLeft;
}
function DisplayPrevUserGuesses()
{
aPrevGuessesString = getPrevGuessesString();
document.getElementById("theUserPrevGuessesLabel").innerHTML = aPrevGuessesString;
}
function DisplayGameStatus()
{
DisplayNumberOfTriesLeft();
DisplayPrevUserGuesses();
}
function CheckUserGuess()
{
aNumberOfTriesLeft = getNumberOfTriesLeft();
if (aNumberOfTriesLeft <= 0) {
// go to the loose page
}
aNumberToGuess = getNumberToGuess();
aUserGuess = Number(theUserValueText.value);
addToPrevGuessesString ("" + aUserGuess);
if (aUserGuess < aNumberToGuess) {
// retry
document.getElementById("theUserHintMessageLabel").innerHTML =
"retry, the number to guess is > higher"
} else if (aUserGuess > aNumberToGuess) {
// retry
document.getElementById("theUserHintMessageLabel").innerHTML =
"retry, the number to guess is < lower"
} else {
// the user wins !!
document.getElementById("theUserHintMessageLabel").innerHTML =
"you win !! " + aUserGuess + " == " + aNumberToGuess + ""
alert ("you win !! " + aUserGuess + " == " + aNumberToGuess + "");
// go to the win page ...
document.location.href = "youwin.html";
}
// ++ theUserTriesCount;
incrUserTriesCount();
aNumberOfTriesLeft = getNumberOfTriesLeft();
if (aNumberOfTriesLeft <= 0) {
// go to the loose page
document.location.href = "youloose.html";
}
DisplayGameStatus();
}
</script>
</head>
<body>
<div>
<h1>
<label>Guess a Number in the Range ( 0 .. </label>
<label id="theMaxNumberToGuessLabel"></label>
<label>)</label>
</h1>
</div>
<div>
<label>you have </label>
<label id="theTriesLeftCountLabel"></label>
<label> tries left</label>
</div>
<p></p>
<div>
<label for="theUserValueText">Enter your Guess: </label>
<input type="text" id="theUserValueText">
<input type="submit" value="Guess" id="ExecUserGuessBtn" onclick="CheckUserGuess()">
</div>
<p></p>
<div>
<label>Prev Guesses: </label>
<label id="theUserPrevGuessesLabel"></label>
</div>
<p></p>
<div>
<label id="theUserHintMessageLabel"></label>
</div>
</body>
</html>
youloose.html
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div>
<h1>
<label>Sorry, You Loose !!</label>
<label>go to </label> Start
</h1>
</div>
</body>
</html>
youwin.html
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div>
<h1>
<label>Congrats, You Win !!</label>
<label>go to </label> Start
</h1>
</div>
</body>
</html>
that's all folks ...

Javascript; html form; user input; display input

I can't figure out why this code won't display the user entered information. I need to have user enter information from the html form, add this info to the arrays, and then display the info (actually, need to do more than this, but can't get past this point). I need the entered information to display on the page. Thanks
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Homework 10</title>
<script type="text/javascript">
//Variables for arrays
var fName = [];
var lName = [];
var tScore = [];
//Variables from user input
var fNameInput = document.getElementById("firstName");
var lNameInput = document.getElementById("lastName");
var tScoreInput = document.getElementById("testScore");
//Variable for display
var display = document.getElementById("display");
//Function to add user info to arrays
function insert() {
fName.push(fNameInput.value);
lName.push(lNameInput.value);
tScore.push(tScoreInput.value);
clearAndShow();
}
//Function to display info entered from array
function clearAndShow() {
fNameInput.value = "";
lNameInput.value = "";
tScoreInput.value = "";
display.innerHTML = "";
display.innerHTML += "First Name: " + fName.join(", ") + "<br/>";
display.innerHTML += "LastName: " + lName.join(", ") + "<br/>";
display.innerHTML += "Test Score: " + tScore.join(", ") + "<br/>";
}
</script>
</head>
<body bgcolor="Cornsilk">
<h2>Average Student Scores</h2>
<form>
<fieldset>
<legend><strong>Enter First, Last Name and Test Score:</strong></legend><br />
<input type="text" id="firstName" placeholder="First name"/><p />
<input type="text" id="lastName" placeholder="Last name"/><p />
<input type="number" id="testScore" placeholder="Test Score"/><p />
<input type="button" value="Save/Show Average" onclick="insert()"/><p />
</fieldset><p />
</form>
<div id="display"></div>
</body>
</html>
I tried to run the code. I got an error like
test.html:23 Uncaught ReferenceError: fName is not defined
You can solve this by moving the variable declaration inside the function.
//Variables for arrays
var fName = [];
var lName = [];
var tScore = [];
//Function to add user info to arrays
function insert() {
var fNameInput = document.getElementById("firstName");
var lNameInput = document.getElementById("lastName");
var tScoreInput = document.getElementById("testScore");
fName.push(fNameInput.value);
lName.push(lNameInput.value);
tScore.push(tScoreInput.value);
clearAndShow();
}
//Function to display info entered from array
function clearAndShow() {
var display = document.getElementById("display");
var fNameInput = document.getElementById("firstName");
var lNameInput = document.getElementById("lastName");
var tScoreInput = document.getElementById("testScore");
fNameInput.value = "";
lNameInput.value = "";
tScoreInput.value = "";
display.innerHTML = "";
display.innerHTML += "First Name: " + fName.join(", ") + "<br/>";
display.innerHTML += "LastName: " + lName.join(", ") + "<br/>";
display.innerHTML += "Test Score: " + tScore.join(", ") + "<br/>";
}
The reason for this is the element is no there when the initial declaration is happening.
Move the script below the body
The main issue is that the Javascript is loaded before the HTML. As a result, when the Javascript attempts to find the element with the element "firstName", it fails to find it because it hasn't been loaded yet.
To fix this, you should move the script tag below the body tag so that the HTML is loaded before it is accessed by the Javascript.
As an added bonus, it improves page load time as the browser doesn't have to wait for the JavaScript to load before rendering the HTML
Example Code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Homework 10</title>
</head>
<body bgcolor="Cornsilk">
<h2>Average Student Scores</h2>
<form>
<fieldset>
<legend><strong>Enter First, Last Name and Test Score:</strong></legend><br />
<input type="text" id="firstName" placeholder="First name"/><p />
<input type="text" id="lastName" placeholder="Last name"/><p />
<input type="number" id="testScore" placeholder="Test Score"/><p />
<input type="button" value="Save/Show Average" onclick="insert()"/><p />
</fieldset><p />
</form>
<div id="display"></div>
</body>
<script type="text/javascript">
//Variables for arrays
var fName = [];
var lName = [];
var tScore = [];
//Variables from user input
var fNameInput = document.getElementById("firstName");
var lNameInput = document.getElementById("lastName");
var tScoreInput = document.getElementById("testScore");
//Variable for display
var display = document.getElementById("display");
//Function to add user info to arrays
function insert() {
fName.push(fNameInput.value);
lName.push(lNameInput.value);
tScore.push(tScoreInput.value);
clearAndShow();
}
//Function to display info entered from array
function clearAndShow() {
fNameInput.value = "";
lNameInput.value = "";
tScoreInput.value = "";
display.innerHTML = "";
display.innerHTML += "First Name: " + fName.join(", ") + "<br/>";
display.innerHTML += "Last Name: " + lName.join(", ") + "<br/>";
display.innerHTML += "Test Score: " + tScore.join(", ") + "<br/>";
}
</script>
</html>

Button click to wait for button click

I have two buttons: Btn1 <input type="button" class="buttons" value="Test">
and Btn2 <input type="button" class="buttons" value="Test2">. I want to be able to click on Btn1 and Btn1 waits for the second button to be pressed and if the second button (Btn2) is pressed the output is Test Test2 is this possible?
I know how to do the button clicks of course but I can't find a solution for the first button to wait for the second one
Try this:-
If you are using Input Buttons like this:-
<input type="button" id="button1" class="buttons" value="Test" />
<input type="button" id="button2" class="buttons" value="Test2" />
<textarea name="test" id="test" rows="8" cols="80" readonly></textarea>
Then use this script:-
<script src="https://code.jquery.com/jquery-1.12.3.min.js" type="text/javascript"></script>
<script type="text/javascript">
var flag1 = false;
var result;
$(document).ready(function () {
$("input[ID$='button1']").click(function () {
flag1 = true;
alert("you clicked button 'Test', Click another button for result");
});
$("input[ID$='button2']").click(function () {
if (flag1 == true) {
//flag1 = false;
if (result)
result = result + " " + $("input[ID$='button1']").val() + " " + $("input[ID$='button2']").val();
else
result = $("input[ID$='button1']").val() + " " + $("input[ID$='button2']").val();
// alert(result);
document.getElementById("test").innerHTML = result;
}
else {
//alert("Please click button 'Test' first");
if (result)
result = result + " " + $("input[ID$='button2']").val();
else
result = $("input[ID$='button2']").val();
document.getElementById("test").innerHTML = result;
}
});
window.onload = function () {
if (flag1 == true) {
//flag1 = false;
if (result)
result = result + " " + $("input[ID$='button1']").val() + " " + $("input[ID$='button2']").val();
else
result = $("input[ID$='button1']").val() + " " + $("input[ID$='button2']").val();
//alert(result);
document.getElementById("test").innerHTML = result;
}
};
});
</script>
If you are using buttons like this:-
<button id="btntest1" class="buttons">Test</button>
<button id="btntest2" class="buttons">Test2</button>
<textarea name="test" id="test" rows="8" cols="80" readonly></textarea>
Then use this script:-
<script src="https://code.jquery.com/jquery-1.12.3.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
$("button[ID$='btntest1']").click(function () {
flag1 = true;
alert("you clicked button 'Test', Click another button for result");
});
$("button[ID$='btntest2']").click(function () {
if (flag1 == true) {
//flag1 = false;
if (result)
result = result + " " + $("button[ID$='btntest1']").html() + " " + $("button[ID$='btntest2']").html();
else
result = $("button[ID$='btntest1']").html() + " " + $("button[ID$='btntest2']").html();
//alert(result);
document.getElementById("test").innerHTML = result;
}
else {
//alert("Please click button 'Test' first");
if (result)
result = result + " " + $("button[ID$='btntest2']").html();
else
result = $("button[ID$='btntest2']").html();
document.getElementById("test").innerHTML = result;
}
});
});
window.onload = function () {
if (flag1 == true) {
//flag1 = false;
if (result)
result = result + " " + $("button[ID$='btntest1']").html() + " " + $("button[ID$='btntest2']").html();
else
result = $("button[ID$='btntest1']").html() + " " + $("button[ID$='btntest2']").html();
//alert(result);
document.getElementById("test").innerHTML = result;
}
};
</script>
Hope this will help you.
depends on your needs.
1- Show button 1 enable
2- Show button 2 disable
3- onclick button 1 :
3.1 : set flags to btn1_clicked = true; and othe var you need
3.2 : Enable button 2
4 onclick button 2 do your output
It's just a global thinking, you can adapt .
So, with the idea of my comment you can do this :
btn1 = document.getElementById('btn-1');
btn2 = document.getElementById('btn-2');
btn1.addEventListener('click', function(){
btn2.removeAttribute('disabled');
btn1.disabled = 'disabled';
});
btn2.addEventListener('click', function(){
btn1.removeAttribute('disabled');
btn2.disabled = 'disabled';
alert(btn2.value);
});
<input id="btn-1" type="button" class="buttons" value="Test">
<input id="btn-2" type="button" class="buttons" value="Test 2" disabled>
Based on my comment...
OnButton1Click -> Set a flag to true
OnButton2Click -> If Variable is true -> "Test Test2" if variable is false -> "Test2"
I created a quick example all vanilla JS.
JSBin Example

javascript function not being called/not working from html form

This is my whole html page
<html>
<head>
<title> text conversion</title>
<script type="text/javascript">
function testResults(form)
{
var str = form.stringn.value;
str.split(" ");
document.write("testing1");
var length = str.length;
var newn = "";
for(var i = 0; i<length; i++)
{
if(str[i].charAt(str[i].length - 1) != ".")
{
str[i] = str[i] + ".";
}
str[i] = str[i] + " ";
str[i].charAt(0) = str[i].charAt(0).toUpperCase();
newn = newn + str[i];
}
document.write(newn);
document.write("testing");
}
</script>
</head>
<body>
<form name="stringform" action="" method="get">
Text: <input type="text" name="stringn"><br>
<input type="button" name="Convert" Value="convert" onClick="testResults(this.form)">
</form>
</body>
</html>
The html is being displayed correctly, but the button does not produce any action. I even tried document.write("testing") below the loop in the javascript, which had no effect, which makes me think the function is not being called at all. The idea of the function is to format the input string to capitalise the first letter of each word, and put a period after each word.
This is my first time trying to use javascript, so possibly I'm doing something wrong that should be obvious?
final solution:
<html>
<head>
<title> text conversion</title>
<script type="text/javascript">
function testResults(form)
{
var str = form.stringn.value;
var strn = str.split(" ");
var length = strn.length;
var newn = "";
for(var i = 0; i<length; i++)
{
if(strn[i].charAt(strn[i].length - 1) != ".")
{
strn[i] = strn[i] + ".";
}
strn[i] = strn[i].charAt(0).toUpperCase() + strn[i].slice(1);
strn[i] = strn[i] + " ";
newn = newn + strn[i];
}
document.write(newn);
}
</script>
</head>
<body>
<form name="stringform" action="" method="get">
Text: <input type="text" name="stringn"><br>
<input type="button" name="Convert" Value="convert" onClick="testResults(this.form)">
</form>
</body>
</html>
This should work. Also, echoing The comments before about using new as a variable.
<html>
<head>
<title> text conversion</title>
<script language="JavaScript">
function testResults(form)
{
var str = form.stringn.value;
var newString = "";
var strList = str.split(" ");
for(var i = 0; i < strList.length; i++){
newWord = strList[i].charAt(0).toUpperCase() + strList[i].slice(1) + ".";
newString += newWord + " ";
}
document.write(newString);
}
</script>
</head>
<body>
<form name="stringform" action="" method="get">
Text: <input type="text" name="stringn"><br>
<input type="button" name="Convert" Value="convert" onClick="testResults(this.form)">
</form>
</body>
</html>
Set <script type="text/javascript"> in your <head>!

Categories