Button click to wait for button click - javascript

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

Related

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 ...

Can't find a way to refactor alert (exercise)

I'm a JS noob trying to make this "hello mr./miss yourname!" clean.
I don't see a way to refactor the alert inside the if/else because then i lose the value of var b.
the JS:
<script>
"use strict";
window.onload = function () {
let form1 = document.getElementById('myForm');
form1.addEventListener('submit', helloYou);
function helloYou() {
let x = document.getElementById("1").value;
let a = document.getElementById('3').value;
if ( a === "M") {
let b = "Mr.";
alert('Hello ' + b + " " + x + "!");
}
else {
let b = "Miss";
alert('Hello ' + b + " " + x + "!");
}
}
}
</script>
the HTML:
<body>
<form id="myForm">
Write your name:
<input type="text" name="yourname" id="1" placeholder="name">
<select name="gender" id="3">
<option value="M">Male</option>
<option value="F">Female</option>
<input type="submit" name="submission" id="2" value="TRY ME">
</form>
</body>
Thanks for any suggestions.
You can use ternary operator
alert('Hello ' + ( a === "M" ? "Mr." : "Miss" ) + " " + x + "!");
i.e.
function helloYou() {
let x = document.getElementById("1").value;
let a = document.getElementById('3').value;
alert('Hello ' + ( a === "M" ? "Mr." : "Miss" ) + " " + x + "!");
}
Assuming you are only needing the value of your gender select for the alert, you could change the value to Mr. and Miss and just alert/print those.
<script>
"use strict";
window.onload = function () {
let form1 = document.getElementById('myForm');
form1.addEventListener('submit', helloYou);
function helloYou() {
let x = document.getElementById("1").value;
let a = document.getElementById('3').value;
alert('Hello ' + a + " " + x + "!");
}
}
</script>
HTML
<body>
<form id="myForm">
Write your name:
<input type="text" name="yourname" id="1" placeholder="name">
<select name="gender" id="3">
<option value="Mr.">Male</option>
<option value="Miss">Female</option>
<input type="submit" name="submission" id="2" value="TRY ME">
</form>
</body>
function helloYou() {
const val = id => document.getElementById(id).value;
alert(`Hello ${val(3) === "M" ? "Mr." : "Miss"} ${val(1)} !`);
}
We can make use of two things 1 tenary to shorten your if logic.
condition ? result : otherResult
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator
and template literals which let you add javascript to a string `string ${javascript}`` using back tics
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals
Something like this?
<script>
"use strict";
window.onload = function () {
let form1 = document.getElementById('myForm');
form1.addEventListener('submit', helloYou);
function helloYou() {
let x = document.getElementById("1").value;
let a = document.getElementById('3').value;
let b = "Miss"
if ( a === "M") {
b = "Mr.";
}
alert('Hello ' + b + " " + x + "!");
}
}
</script>
Just adding this as an option, quite clean :)
const helloYou = () => {
let name = document.getElementById('1').value
let gender = document.getElementById('3').value
const prefix = gender === 'M' ? 'Mr.' : 'Miss'
alert(`Hello ${prefix} ${name}!`)
}

How do I display results?

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;
}

Passing entered text field value into getJSON string?

I am trying to add some functionality to the entered tags in this image searcher using the flickr API. I have it working but it only works when I write the string within the code. For example I have "cats" in the for now. My goal is the pass the entered value from the textbox (id="textbox1") into the tags in the script above. I want to be able to search from the text box and not go into the code. Thanks for any tips/advice!
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<html>
<head>
<script type="text/javascript" src="jquery-1.11.2.js"></script>
</head>
<body>
<script type="text/javascript">
$(document).ready(function() {
$("#button").click(function() {
$("#images").empty();
$.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?", {
tags: "cats",
tagmode: "any",
format: "json"
}, function(data) {
console.log(data);
$.each(data.items, function(i, item) {
$(".buttonclick").remove();
$('<img/>').attr("src", item.media.m).appendTo('#images');
if (i == 1) return false;
});
});
});
$('#images').on('click', 'img', function() {
var $imgClone = $(this).clone().attr('src', $(this).attr('src').replace('_m.', '_b.'));
$('#main').html($imgClone);
});
});
$(document).ready(function() {
var counter = 2;
$("#addButton").click(function() {
if (counter > 10) {
alert("Only 10 textboxes allow");
return false;
}
var newTextBoxDiv = $(document.createElement('div')).attr("id", 'TextBoxDiv' + counter);
newTextBoxDiv.after().html('<label></label>' +
'<input type="text" name="textbox' + counter +
'" id="textbox' + counter + '" value="" >');
newTextBoxDiv.appendTo("#TextBoxesGroup");
counter++;
});
$("#removeButton").click(function() {
if (counter == 1) {
alert("No more textbox to remove");
return false;
}
counter--;
$("#TextBoxDiv" + counter).remove();
});
$("#getButtonValue").click(function() {
var msg = '';
for (i = 1; i < counter; i++) {
msg += "\n Textbox #" + i + " : " + $('#textbox' + i).val();
}
alert(msg);
});
});
</script>
<h1>Image Search</h1>
<button type="button" id="button">Search</button>
<input type='button' value='Remove Tag' id='removeButton'>
<div id='TextBoxesGroup'>
<div id="TextBoxDiv1">
<input type='textbox' id='textbox1'>
<input type='button' value='Add tag' id='addButton'>
</div>
</div>
<div id="images" /></div>
</body>
</html>
In $.getJSON you can switch "cats" with
$("#textbox1").val(),
and it will use the value of the input (whatever the user has typed into it) as the value of "tags".
//Stuff before
tags:$("#textbox1").val(),
//Stuff after
I hope this helped!
Edit:
In case you want to learn more about jQuery's .val(), you can read the documentation here.

Add submit button to jquery search form

I am trying to add a submit and a clear button to a quicksearch form in flexigrid. At the moment, when a user searches, they have press the enter key (13). So in conjunction with that, I would also like buttons that search and clear. I know I did this before, but cannot find the code after a restore. Many thanks
//add search button
if (p.searchitems) {
$('.pDiv2', g.pDiv).prepend("<div class='pGroup'> <div class='pSearch pButton'><span></span></div> </div> <div class='btnseparator'></div>");
$('.pSearch', g.pDiv).click(function () {
$(g.sDiv).slideToggle('fast', function () {
$('.sDiv:visible input:first', g.gDiv).trigger('focus');
});
});
//add search box
g.sDiv.className = 'sDiv';
var sitems = p.searchitems;
var sopt = '', sel = '';
for (var s = 0; s < sitems.length; s++) {
if (p.qtype == '' && sitems[s].isdefault == true) {
p.qtype = sitems[s].name;
sel = 'selected="selected"';
} else {
sel = '';
}
sopt += "<option value='" + sitems[s].name + "' " + sel + " >" + sitems[s].display + " </option>";
}
if (p.qtype == '') {
p.qtype = sitems[0].name;
}
$(g.sDiv).append("<div class='sDiv2'>" + p.findtext +
" <input type='text' value='" + p.query +"' size='30' name='q' class='qsbox' /> "+
" <select name='qtype'>" + sopt + "</select></div>");
//Split into separate selectors because of bug in jQuery 1.3.2
$('input[name=q]', g.sDiv).keydown(function (e) {
if (e.keyCode == 13) {
g.doSearch();
}
});
$('select[name=qtype]', g.sDiv).keydown(function (e) {
if (e.keyCode == 13) {
g.doSearch();
}
});
$('input[value=Clear]', g.sDiv).click(function () {
$('input[name=q]', g.sDiv).val('');
p.query = '';
g.doSearch();
});
$(g.bDiv).after(g.sDiv);
}
ok you can try something simple like that :
$('.sDiv2').append("<input type='submit' value='submit' name='submit' /><input type='reset' value='reset' name='reset' />");
After you set listeners like you did for the others input

Categories