setting variable value on click - javascript

Im new in programming and im trying to make my first project in js - hangman game (https://en.wikipedia.org/wiki/Hangman_(game))
So basically i got two buttons in my HTML file, lets say its look like this:
<button id="movies">Movies</button>
<button id="animals">Animals</button>
i want this buttons to be responsible for changing categories in my game. In js i got:
var movies = ["Shawshank Redemption","Alice in a Wonderland"];
var animals = ["Blue whale","Raspberry Crazy-Ant"];
var choice = 1;
if (choice === 0){
var pwdDraw = Math.floor(Math.random() * movies.length);
var pwd = movies[pwdDraw];
pwd = pwd.toUpperCase();
document.write(pwd);
}
else if (choice === 1){
var pwdDraw = Math.floor(Math.random() * animals.length);
var pwd = animals[pwdDraw];
pwd = pwd.toUpperCase();
document.write(pwd);
}
and this is the place where im stucked, i dont know how change var choice by clicking button (also i want to reload page after click). Im at the beginning on my way with js, so i want this code to be pure js, not any customized library.

<button onclick="changeCategory(number)">Click me</button>
<script>
function changeCategory() {
//[..]
}
</script>
https://www.w3schools.com/jsref/event_onclick.asp

thanks a lot for feedback, but i still have some troubles of implementing this js changes, When im doing it on new file with only category changer everything is running smooth. But when i try to add this to my existing code its doesnt work at all. Here you got my code:
codepen.io/iSanox/project/editor/DGpRrY/

First of all, don't put those <br> in JS code like that.
If you want to try to get the choice by clicking on the button then here's how you can do it:
HTML
<button id="movies" class="choice" value="0">Movies</button>
<br/>
<button id="animals" class="choice" value="1">Animals</button>
JS
var buttons = document.querySelectorAll(".choice");
function doSomething(e)
{
// You can get choice value by either doing:
var choice = e.target.value;
// OR
var choice = this.value;
// Continue your work here
}
for(var i = 0; i < buttons.length; i++)
{
buttons[i].addEventListener("click", doSomething);
}
Feel free to ask any questions.

Simply you can use onclick event. After some changes your code should look like this.
var movies = ["Shawshank Redemption", "Alice in a Wonderland"];
var animals = ["Blue whale", "Raspberry Crazy-Ant"];
var catname = document.getElementById('cat-name');
function selectCategory(choice) {
var pwd, pwdDraw;
if (choice === 0) {
pwdDraw = Math.floor(Math.random() * movies.length);
pwd = movies[pwdDraw];
} else if (choice === 1) {
pwdDraw = Math.floor(Math.random() * animals.length);
pwd = animals[pwdDraw];
}
pwd = pwd.toUpperCase();
catname.innerText = pwd;
}
<p>Choose Category</p>
<button id="movies" onclick="selectCategory(0)">Movies</button>
<button id="animals" onclick="selectCategory(1)">Animals</button>
<div id="cat-name"></div>
Even better with Object and Arrays
var categories = {
movies: ["Shawshank Redemption", "Alice in a Wonderland"],
animals: ["Blue whale", "Raspberry Crazy-Ant"]
};
var catname = document.getElementById('cat-name');
function selectCategory(choice) {
var pwdDraw = Math.floor(Math.random() * categories[choice].length);
var pwd = categories[choice][pwdDraw];
pwd = pwd.toUpperCase();
catname.innerText = pwd;
}
<p>Choose Category</p>
<button id="movies" onclick="selectCategory('movies')">Movies</button>
<button id="animals" onclick="selectCategory('animals')">Animals</button>
<div id="cat-name"></div>

Related

Javascript Information Needed

Looking for a little guidance. I know its something small and dumb but I'm completely drawing a blank at this point and could use some help. I'm trying to create a mobile app for my class that needs a dynamic table for my results. I'm attempting to create a user input to select a number of "Random powerball tickets" and the table would give "Ticket 1 / Random Numbers." I have managed to create the random number generator onclick but cant for the life of me figure out the rest.
HTML- I dont remember how to connect the user input to the button and repeat x amount of times to match.
<div data-role="content">
<p>This will be a simple application that provide generated powerball numbers between 1-69.</p>
</div>
<div>
<button id="button" onClick="winningNumbers()" >Powerball Numbers</button>
</div>
<p id="outcome"></p>
<table id="data">
</table>
Current Javascript
var powerball;
function powerballNumbers(max) {
var ranNum = Math.floor((Math.random() * max) + 1);
return ranNum;
}
function main() {
powerball = [];
for (i = 0; i < 5; i++) {
powerball.push(powerballNumbers(69));
}
powerball.push(powerballNumbers(26));
}
function winningNumbers() {
main();
var totalTickets = document.getElementById("outcome");
totalTickets.innerText = powerball;
}
Thinking of something like this for the table but know it's not correct
function updateTable(ticketNumber, powerballNumber) {
var dataTable = document.getElementById("data");
dataTable.innerHTML = "";
// create rows of data based on given arrays
(Not sure what to put here)
// create header row
var thead = dataTable.createTHead();
var row = thead.insertRow(0);
var tableHeaders = ["Ticket", "Numbers"];
for (var i = 0; i < tableHeaders.length; i++) {
var headerCell = document.createElement("th");
headerCell.innerHTML = tableHeaders[i];
row.appendChild(headerCell);
}
}
I'm not entirely sure of what your end goal is, but the best I understand is you want to generate some tickets with an ID, and each ticket has 5 numbers? If so, I simply generated a ticket ID, and 5 numbers to go with that ticket. Then in the update table function, I've simplified it so it can focus on just appending new rows. If I've missed the mark please comment below and/or update your question.
Just some side comments.
Avoid using attributes for click events, it's unreliable at best.
Don't hestiate to use HTML when HTML is the answer. Your original update table method was going to build out a table? It only adds a headache, not ease.
Good job on leveraging the tools <table> gives us!
var powerball;
function powerballNumbers(max) {
var ranNum = Math.floor((Math.random() * max) + 1);
return ranNum;
}
function main() {
let i = 0
interval = setInterval(function() {
updateTable(powerballNumbers(9999), [powerballNumbers(69),
powerballNumbers(69),
powerballNumbers(69),
powerballNumbers(69),
powerballNumbers(69)
]);
i++;
if (i > 5) {
clearInterval(interval);
}
}, 500)
}
function winningNumbers() {
main();
var totalTickets = document.getElementById("outcome");
totalTickets.innerText = powerball;
}
function updateTable(ticket, powerballNumber) {
var dataTable = document.getElementById("data");
let newRow = dataTable.insertRow();
let ticketCell = newRow.insertCell();
ticketCell.textContent = ticket;
let numbers = newRow.insertCell();
numbers.textContent = powerballNumber.join(", ");
}
<div data-role="content">
<p>This will be a simple application that provide generated powerball numbers between 1-69.</p>
</div>
<div>
<button id="button" onClick="winningNumbers()">Powerball Numbers</button>
</div>
<p id="outcome"></p>
<table id="data" border=1>
<thead>
<tr>Ticket Number</tr>
<tr>Numbers</tr>
</thead>
</table>

How to validate an user answer button click javascript

Currently I'm trying to create a quiz, right now it displays the first question with 4 answer choices after the start button I am stuck on how to retrieve the answer. The user clicks, check to see if its correct and loop to the next question. I just want to give the user one chance per question and move on regardless if it's correct or not. If their answer is wrong I will remove seconds from the timer. I have the questions, answer choices, and correct answers in arrays.
<div class="card-body">
<p id="header">
You have 75 seconds to complete this asessment.
Every incorrect answer will cost you time.
<br>
</p>
<button id="start-button" class="btn">Start</button>
<div id="start-game" style="visibility: hidden">
<button id="option0" data-index="0"></button><br>
<button id="option1" data-index="1"></button><br>
<button id="option2" data-index="2"></button><br>
<button id="option3" data-index="3"></button><br>
</div>
</div>
<script src="./script.js"></script>
var timerEl = document.getElementById("timer");
var start = document.getElementById("start-button");
var questionEl = document.getElementById("header");
var option0 = document.getElementById("option0");
var option1 = document.getElementById("option1");
var option2 = document.getElementById("option2");
var option3 = document.getElementById("option3");
var intials = document.getElementById("user-initials");
var buttonEl = document.getElementById("start-game");
var totalTime = 75;
var elapsedTime = 0;
var questionNum = 0;
var questions =["The condition in an if/else statement is enclosed with in _______",
"Arrays in JavaScript can be used to store ______",
"Commonly used data types do not include ______",
"String values must be enclosed within _____ when being assigned to variables"];
var answers =[question1= ["Quotes","Curly brackets","Parentheses","Square brackets"],
question2= ["Numbers and strings","Other arrays","Booleans","All of the above"],
question3= ["Strings","Booleans","Alerts","Numbers"],
question4= ["Commas","Curly brackets","quotes","parentheses"],
];
var correctAnswers = [2,3,2,2];
start.addEventListener("click", function(){
timer();
displayQuestion();
start.style.visibility = "hidden";
buttonEl.style.visibility = "visible";
});
function timer(){
var timerInterval = setInterval(function(){
totalTime --;
timerEl.textContent = totalTime;
if(totalTime === 0){
clearInterval(timerInterval);
endQuiz();
return;
}
}, 1000);
}
function newQuiz(){
questionEl.textContent = (questions[0]);
};
function displayQuestion(){
for( var i = 0; i < questions.length ; i++){
questionEl.textContent=(questions[i]);
option0.textContent=(answers[i][0]);
option1.textContent=(answers[i][1]);
option2.textContent=(answers[i][2]);
option3.textContent=(answers[i][3]);
console.log(i);
return;
}
}
Hi I will try to provide an easy solution to your question without using any kind of difficult javascript syntax so here goes..
First in your html file update the option button and add a class property called clickOption(you can change the class name if you want, but be sure to change in other places in script.js as well). The code is shown below.
<button id="option0" class="clickOption" data-index="0"></button><br>
<button id="option1" class="clickOption" data-index="1"></button><br>
<button id="option2" class="clickOption" data-index="2"></button><br>
<button id="option3" class="clickOption" data-index="3"></button><br>
Now in your script.js file add the line of code shown below. I have added inline comments for better understanding
// get all elements with class clickoption i.e all option buttons
var elements = document.getElementsByClassName("clickOption");
//use the below array to track the selected answers
var selectedAnswers = [];
var clickOption = function() {
/** Here I have reached the end of the test and,
I am logging the array of user-selected options.
This array can be compared with correctAnswers array
to determine whether the answer is correct or not **/
if(questionNum >= questions.length) {
console.log(selectedAnswers);
return;
}
/**Get the option value that was clicked.
Here I am using parseInt because,
the data-index attribute value will be in string format,
and the correctAnswers array is in Number format so it is better,
to keep the selectedAnswers array in Number format as it will faciliate
easier data comparison**/
var selectedOption = parseInt(this.getAttribute('data-index'));
// add the selected option to the selectedAnwsers Array
selectedAnswers.push(selectedOption);
/** here I am assuming that you are using the questionNum variable
to track the current question Number **/
questionNum += 1;
/** here I am again checking if I have reached the end of test and
thus log the answers
Instead of logging the answer you can create a function
that compares the result and display it on screen **/
if(questionNum >= questions.length) {
console.log(selectedAnswers);
return;
}
// update the next question text
questionEl.textContent = questions[questionNum];
// update next options
displayQuestion(questionNum);
}
//loop through all the elements with class clickOption
for (var i = 0; i < elements.length; i++) {
elements[i].addEventListener('click', clickOption);
}
start.addEventListener("click", function() {
timer();
/** I have updated the displayQuestion call implementation
so that the function is called with a parameter
(here the parameter it is zero) **/
displayQuestion(questionNum);
start.style.visibility = "hidden";
buttonEl.style.visibility = "visible";
});
/**Finally I have updated the display question method
so that it updates the option buttons based on the index parameter **/
function displayQuestion(index){
questionEl.textContent = questions[index];
option0.textContent = answers[index][0];
option1.textContent = answers[index][1];
option2.textContent = answers[index][2];
option3.textContent = answers[index][3];
}
Hope this solution helps you. Happy Coding!

"reuse" a JavaScript code for multiple buttons

I am fairly new to JavaScript,
I have ben working on a simple if else script to change the color of at button, depending on the status of a variable that I get from a plc (Siemens S7-1200).
The script is working fine and the color of the button is changing.
But I have 10 buttons that I want to run this script on.
Is it possible to “reuse” the script so that I don’t have to copy the script and change the variables for every button
T
<script>
var tag = ':="web_DB".outtag1:'
var button = "button1"
window.onload = function() {
if (tag == 1) {
document.getElementById(button).style.backgroundColor = 'green';
} else{
document.getElementById(button).style.backgroundColor = 'red';
}
}
</script>
<form>
<input type="submit" id="button1" value="button">
<input type="hidden" name='"web_DB".intag1' value ="1">
</form>
It's hard to be sure since you haven't posted all your code and what you have posted doesn't actually work but I think you're looking for something like this.
const tags = [
':="web_DB".outtag1:',
':="web_DB".outtag2:',
//...
':="web_DB".outtag10:'
];
window.onload = function() {
for (let i = 0; i <= 9; i++) {
const color = (tags[i] == 1) ? 'green' : 'red';
document.getElementById('button' + (i+1)).style.backgroundColor = color;
}
}

Remove checked checkboxes

I am making a To-do list, where I want to be able to add new tasks, and delete tasks that are checked off. However, it seems my function just deletes all tasks, not just the ones that are checked off. Neither does it seem to allow new tasks to be added.
html:
<h1 id="title"> To-do list</h1>
<div id="task_area">
</div>
<input type="text" id="putin"></input>
<button id="add">add</button>
javascript:
<button id="clear">Clear completed tasks</button>
var tasks = document.getElementById("task_area")
var new_task = document.getElementById("add")
var clear = document.getElementById("clear")
new_task.addEventListener("click", function() {
var putin = document.getElementById("putin")
var input = document.createElement('input')
input.type = "checkbox"
var label = document.createElement('label')
label.appendChild(document.createTextNode(putin.value))
task_area.appendChild(input)
task_area.appendChild(label)
})
clear.addEventListener("click", function() {
for (i = 0; i < task_area.children.length; i++) {
if (task_area.children[i].checked === true) {
task_area.remove(tasks.children[i])
}
}
})
jsfiddle: https://jsfiddle.net/4coxL3um/
.remove removes the element you are calling it from, and doesn't take an argument for what to remove. The following:
task_area.remove(tasks.children[i])
should be
tasks.children[i].remove()
EDIT: As Mononess commented below, this will only remove the checkboxes and not the labels. While you could delete both using Jayesh Goyani's answer below, it's probably better that each input/label pair be wrapped in a single div or span for easier management.
You could try adding an event listener to each child of task_area that calls the below function. Haven't gotten a chance to test it out, and may not fulfill all of your requirements, but should get the job done.
function removeClicked() {
this.parentNode.removeChild(this);
}
Please try with the below code snippet. Below code will help you to remove selected checkbox with label.
<body>
<h1 id="title">To-do list</h1>
<div id="task_area">
</div>
<input type="text" id="putin" />
<button id="add">add</button>
<button id="clear">Clear completed tasks</button>
<script>
var tasks = document.getElementById("task_area")
var new_task = document.getElementById("add")
var clear = document.getElementById("clear")
new_task.addEventListener("click", function () {
var putin = document.getElementById("putin")
var input = document.createElement('input')
input.type = "checkbox"
var label = document.createElement('label')
label.appendChild(document.createTextNode(putin.value))
task_area.appendChild(input)
task_area.appendChild(label)
//document.getElementById("task_area").innerHTML = putin.value
})
clear.addEventListener("click", function () {
for (i = 0; i < task_area.children.length; i++) {
if (task_area.children[i].checked === true) {
tasks.children[i].nextSibling.remove();
tasks.children[i].remove();
}
}
})
</script>
</body>
Please let me know if any concern.

localstorage how to save a button

I managed to save the text that is in the input field but the problem is that i do not know how to save the button. The buttons turn white when i click on them and the price of that seat will be visible in the input field. The price saves but the button does not stay white.
<script>
function changeBlue(element) {
var backgroundColor = element.style.background;
if (backgroundColor == "white") {
element.style.background = "blue";
add(-7.5)
} else {
element.style.background = "white";
add(7.5)
}
}
function add(val) {
var counter = document.getElementById('testInput').value;
var b = parseFloat(counter,10) + val;
if (b < 0) {
b = 0;
}
document.getElementById('testInput').value = b;
return b;
}
function save(){
var fieldValue = document.getElementById("testInput").value;
localStorage.setItem("text", fieldValue)
var buttonStorage = document.getElementsByClass("blauw").value;
localStorage.setItem("button", buttonStorage)
}
function load(){
var storedValue = localStorage.getItem("text");
if(storedValue){
document.getElementById("testInput").value = storedValue;
}
var storedButton = localStorage.getItem("button");
if(storedButton){
document.getElementsByClass("blauw").value = storedButton;
}
}
</script>
<body onload="load()">
<input type="text" id="testInput"/>
<input type="button" id="testButton" value="Save" onclick="save()"/>
<input class="blauw" type="button" id="testButton2" value="click me to turn white"
style="background-color:blue" onclick="changeBlue(this)">
<input class="blauw" type="button" id="testButton2" value="click me to turn white"style="background-color:blue" onclick="changeBlue(this)">
</body>
i made a small sample of what i want to do. And i do not want to use the Id's of the buttons because i have like 500 of them in a table.
That's because getElementsByClass (it's getElementsByClassName btw) returns a node list of all the elements with that class.
To make it work, you need to go through all the items in the list, using a for-loop, and set the value of each individual element to the localStorage-value.
See these links for more information:
Link 1
Link 2
Very small mockup to give you an idea:
(In the JS, I put in comments the lines of code you would be using for your situation.)
function changeValues() {
var list = document.getElementsByClassName("child"); //var list = document.getElementsByClassName("blauw");
for (var i=0; i<list.length; i++) {
list[i].innerHTML = "Milk"; //list[i].value = storedButton;
}
}
<ul class="example">
<li class="child">Coffee</li>
<li class="child">Tea</li>
</ul>
<p>Click the button to change the text of the first list item (index 0).</p>
<button onclick="changeValues()">Try it</button>

Categories

Resources