How can I change paragraph content on button click with if statement? - javascript

Trying to display different messages inside the p element for when someone clicks on one of the three buttons. But it only displays the first message (reply) for all the buttons.
Can't see what I have done wrong...
HTML
<div class="options">
<div id="good" class="btn"></div>
<div id="idk" class="btn"></div>
<div id="bad" class="btn"></div>
</div>
JavaScript
let good = document.getElementById("good");
let idk = document.getElementById("idk");
let bad = document.getElementById("bad");
let main = document.querySelector(".main");
let reply;
document.getElementById("good"), document.getElementById("idk"), document.getElementById("bad")].forEach(option => {
option.addEventListener("click", () => {
if (good.clicked = true) {
main.style.display = "block";
reply = "Hey";
} else if (idk.clicked = true) {
main.style.display = "block";
reply = "Well yeah";
} else if (bad.clicked = true) {
main.style.display = "block";
reply = "123";
}
document.getElementById("reply").innerHTML = reply;
});
});

const good = document.getElementById("good");
const idk = document.getElementById("idk");
const bad = document.getElementById("bad");
const main = document.querySelector(".main");
const reply = document.getElementById("reply");
const messageTypes = {
good: 'Hey',
idk: 'Well yeah',
bad: '123 BAD'
};
[good, idk, bad].forEach(option => {
option.addEventListener("click", (e) => {
reply.innerHTML = messageTypes[e.target.id];
});
});
<div class="options">
<button id="good" class="btn">good</button>
<button id="idk" class="btn">idk</button>
<button id="bad" class="btn">bad</button>
</div>
<div class="main"><div>
<div id="reply"></div>
Use const for everything, create a separate message dictionary for every message and just map it against the id. You don't need to use jQuery.

If your real use case is as simple as your example, I would consider maybe using different event listeners with different logic inside them. But if you want to use the same event listener, then you can use event.target.id to know which button was clicked:
[document.getElementById("good"), document.getElementById("idk"), document.getElementById("bad")].forEach(option => {
option.addEventListener("click", (event) => {
switch (event.target.id) {
case "good":
reply = "Hey";
break;
case "idk":
reply = "Well yeah";
break;
case "bad":
reply = "123";
break;
}
main.style.display = "block";
document.getElementById("reply").innerHTML = reply;
});
});
Here you can see it working (note that I removed main.style.display = "block"; in the following example since I don't know what main is in your original code):
[document.getElementById("good"), document.getElementById("idk"), document.getElementById("bad")].forEach(option => {
option.addEventListener("click", (event) => {
switch (event.target.id) {
case "good":
reply = "Hey";
break;
case "idk":
reply = "Well yeah";
break;
case "bad":
reply = "123";
break;
}
document.getElementById("reply").innerHTML = reply;
});
});
<div class="options">
<div id="good" class="btn">good</div>
<div id="idk" class="btn">idk</div>
<div id="bad" class="btn">bad</div>
</div>
<div id="reply"/>

It could be something like that:
let good = document.getElementById("good");
let idk = document.getElementById("idk");
let bad = document.getElementById("bad");
let main = document.querySelector(".main");
let reply;
[good, idk, bad].forEach(option => {
option.addEventListener("click", (e) => {
if (e.target == good) {
main.style.display = "block";
reply = "Hey";
} else if (e.target == idk) {
main.style.display = "block";
reply = "Well yeah";
} else if (e.target == bad) {
main.style.display = "block";
reply = "123";
}
document.getElementById("reply").innerHTML = reply;
});
});
<div class="options">
<div id="good" class="btn">good</div>
<div id="idk" class="btn">idk</div>
<div id="bad" class="btn">bad</div>
</div>
<div class="main"><div>
<div id="reply"></div>

I'd be tempted to use explicit event handlers for each of the buttons rather than a generic handler that then tests all three conditions.
You can reduce the code duplication by using a function to handle the display update of the main element and the setting of reply.
Something like the following shows this in action:
let good = document.getElementById("good");
let idk = document.getElementById("idk");
let bad = document.getElementById("bad");
let main = document.querySelector(".main");
good.addEventListener("click", function(e) {
showMain("Good");
});
idk.addEventListener("click", function(e) {
showMain("Well yeah");
});
bad.addEventListener("click", function(e) {
showMain("123");
});
function showMain(replyText) {
main.style.display = "block";
document.getElementById("reply").innerHTML = replyText;
}
.main {
background-color: red;
display: none;
height: 100px;
width: 100px;
}
<button id="good">Good</button>
<button id="idk">Idk</button>
<button id="bad">Bad</button>
<div class="main"></div>
<div id="reply"></div>

You can instead, do something like this for what you want
In Pure VanillaJS
[document.getElementById("good"), document.getElementById("idk"), document.getElementById("bad")].forEach(option => {
option.addEventListener("click", (event) => {
if (event.target.id == "good") {
main.style.display = "block";
reply = "Hey";
} else if (event.target.id == "idk") {
main.style.display = "block";
reply = "Well yeah";
} else if (event.target.id == "bad") {
main.style.display = "block";
reply = "123";
}
document.getElementById("reply").innerHTML = reply;
});
});

= is used for assignments however == is used to check equality of two strings in javascript
[] ...addEventListener("click", (e) => {
if (good.id == e.target.id) {
main.style.display = "block";
reply = "Hey";
}
// and so on
document.getElementById("reply").innerHTML = reply;
});
var btn1=document.getElementById('btn1')
var btn2=document.getElementById('btn2')
var btn3=document.getElementById('btn3')
// jquery way
$('.btn').on("click",function(e){
$("#msg").html(e.target.id+" clicked");
})
// javascript way
var classname = document.getElementsByClassName("btn");
for (var i = 0; i < classname.length; i++) {
classname[i].addEventListener("click", function(e){
document.getElementById('msg').innerHTML =e.target.id+' clicked';
})
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
<input type="button" id="btn1" class="btn" value="button 1">
<input type="button" id="btn2" class="btn" value="button 2">
<input type="button" id="btn3" class="btn" value="button 3">
<p id="msg"></p>

Related

How can I prevent a user from clicking a button multiple times?

I am currently creating a game where the goal is to guess flags that are displayed, with a scoring system. It works well overall, but I would like it if, when the answer is validated and correct (and the score is incremented), it is not possible to press it again, otherwise it allows the score to be incremented ad infinitum.
Similarly, I have a button that gives the answer if the user does not find it. I would like it to be impossible for the user to give an answer and validate it in this case.
I tried to use the function javascript element.disabled = true but it blocks the answer for the questions according to this is not the purpose. To limit I also tried to make a click counter that locks at 1 but it has no effect I think.
I would like to know if someone could explain me the steps to follow and instructions.
function getRandomInt(max) {
return Math.floor(Math.random() * max);
}
let flag = "Cambodia";
ans = false;
answerDisplayed = false
score = 0;
function getVal() {
const inputValue = document.querySelector('input').value;
if (inputValue.toLowerCase() != flag.toLowerCase()) {
document.querySelector('.result').classList.add("result-false");
document.querySelector('.result').innerHTML = 'Mauvaise Réponse';
document.querySelector('.result').style.color = "red";
ans = false;
} else {
document.querySelector('.result').classList.add("result-true");
document.querySelector('.result').innerHTML = 'Bonne Réponse';
document.querySelector('.result').style.color = "green";
ans = true;
score = score + 1;
document.querySelector('.score').innerHTML = score;
}
}
function getData() {
var json = 'https://cdn.jsdelivr.net/npm/country-flag-emoji-json#2.0.0/dist/index.json'
fetch(json)
.then(data => data.json())
.then(data => {
const randomInt = getRandomInt(data.length);
console.log(data[randomInt]);
var image = document.getElementById("flag");
image.src = data[randomInt].image;
flag = data[randomInt].name;
});
document.querySelector('.result').innerHTML = '';
document.querySelector('.result').innerHTML = '';
}
function getAnswer() {
document.querySelector('.result').innerHTML = flag;
document.querySelector('.result').style.color = "white";
document.querySelector('.next').disabled = true;
document.querySelector('.skip').innerHTML = 'Drapeau suivant';
}
function skip() {
getData();
document.querySelector('.next').disabled = false;
document.querySelector('.skip').innerHTML = 'Je passe';
}
function next() {
if (ans == true) {
getData();
inputValue = "";
} else {
document.querySelector('.result').innerHTML = 'Entrez la bonne réponse';
}
}
<link href="https://fonts.googleapis.com/css2?family=Outfit:wght#400;500;600&display=swap" rel="stylesheet">
<script>
window.onload = function() {
getData();
document.querySelector('.score').innerHTML = score;
};
</script>
<h1>GuessTheFlag</h1>
<div class="app">
<div class="flagCanva">
<h3>Score : <span class="score"></span></h3>
<img width="100" id="flag" src="" alt="">
</div>
<div class="inputAns">
<input type="text" name="flagName" placeholder="Nom du pays">
<button type="submit" onclick="getVal()" class="validateBtn btn">Je valide</button>
</div>
<p class="answerText"></p>
<p class="result"></p><br>
<div class="btns">
<button onclick="next()" class="next btn2">Suivant</button>
<button onclick="getAnswer()" class="answer btn2">Réponse</button>
<button onclick="skip()" class="skip btn2">Je passe !</button>
</div>
<p>*Les réponses doivent être données en Anglais. <br>Pensez à valider votre réponse avant de passer à la suivante</p>
</div>
The issue you're running into is due to the use of onclick inside of the button. A better approach is to use addEventListener and removeEventListener to add/remove event callbacks.
function getRandomInt(max) {
return Math.floor(Math.random() * max);
}
let flag = "Cambodia";
ans = false;
answerDisplayed = false
score = 0;
const validateButton = document.getElementById("validate");
validateButton.addEventListener("click", getVal);
function getVal() {
const inputValue = document.querySelector('input').value;
if (inputValue.toLowerCase() != flag.toLowerCase()) {
document.querySelector('.result').classList.add("result-false");
document.querySelector('.result').innerHTML = 'Mauvaise Réponse';
document.querySelector('.result').style.color = "red";
ans = false;
alert(false);
} else {
document.querySelector('.result').classList.add("result-true");
document.querySelector('.result').innerHTML = 'Bonne Réponse';
document.querySelector('.result').style.color = "green";
ans = true;
score = score + 1;
document.querySelector('.score').innerHTML = score;
}
validateButton.removeEventListener("click", getVal);
}
function getData() {
var json = 'https://cdn.jsdelivr.net/npm/country-flag-emoji-json#2.0.0/dist/index.json'
fetch(json)
.then(data => data.json())
.then(data => {
const randomInt = getRandomInt(data.length);
console.log(data[randomInt]);
var image = document.getElementById("flag");
image.src = data[randomInt].image;
flag = data[randomInt].name;
});
document.querySelector('.result').innerHTML = '';
document.querySelector('.result').innerHTML = '';
}
function getAnswer() {
document.querySelector('.result').innerHTML = flag;
document.querySelector('.result').style.color = "white";
document.querySelector('.next').disabled = true;
document.querySelector('.skip').innerHTML = 'Drapeau suivant';
}
function skip() {
getData();
document.querySelector('.next').disabled = false;
document.querySelector('.skip').innerHTML = 'Je passe';
validateButton.addEventListener("click", getVal);
}
function next() {
if (ans == true) {
getData();
inputValue = "";
} else {
document.querySelector('.result').innerHTML = 'Entrez la bonne réponse';
}
validateButton.addEventListener("click", getVal);
}
<link href="https://fonts.googleapis.com/css2?family=Outfit:wght#400;500;600&display=swap" rel="stylesheet">
<script>
window.onload = function() {
getData();
document.querySelector('.score').innerHTML = score;
};
</script>
<h1>GuessTheFlag</h1>
<div class="app">
<div class="flagCanva">
<h3>Score : <span class="score"></span></h3>
<img width="100" id="flag" src="" alt="">
</div>
<div class="inputAns">
<input type="text" name="flagName" placeholder="Nom du pays">
<button type="submit" id="validate" class="validateBtn btn">Je valide</button>
</div>
<p class="answerText"></p>
<p class="result"></p><br>
<div class="btns">
<button onclick="next()" class="next btn2">Suivant</button>
<button onclick="getAnswer()" class="answer btn2">Réponse</button>
<button onclick="skip()" class="skip btn2">Je passe !</button>
</div>
<p>*Les réponses doivent être données en Anglais. <br>Pensez à valider votre réponse avant de passer à la suivante</p>
</div>
The first idea that crosses my mind is a variable that is set to false, whenever you want to prevent users from a certain action.
var userCanClickAnswerButton = true;
When user clicks the button, the variable is set to false:
userCanClickAnswerButton = false;
So in the click event handler of the answer button you can insert this as first command:
if(!userCanClickAnswerButton) {
return;
}
So the function will not execute any further commands when you don't want the user to click.

JavaScript - Comments duplicating on another div

I am creating a comment box and I managed to append whatever I type to a div I wanted, however I have added another input and trying to append that along with the comments, however when I do this the second time,it appends both the previous and current comment therefore the previous comment duplicates. I know I'm doing something wrong in my display_commnents function, however I'm not entirely sure what it could be, basically I just want whatever is entered on both title and comments to append on the comment-box with title on top and comment just below. Below is my code:
<div class="container">
<h1>Write New Post</h1>
<form>
<input id="title" type="text" placeholder="Title" value="">
<textarea id="" placeholder="Leave us a comment" value=""></textarea>
<input id="giphy" type="text">
<div class="btn">
<input id="submit" type="submit" value="comment">
<button id="clear">Cancel</button>
</div>
</form>
</div>
<div class="comments">
<h2>Comments</h2>
<div id="comment-box" value="submit">
</div>
</div>
And this is my JS code:
const title = document.querySelector('#title')
const field = document.querySelector('textarea');
const textBackUp = title.getAttribute('placeholder')
const backUp = field.getAttribute('placeholder')
const btn = document.querySelector('.btn');
const clear = document.getElementById('clear')
const submit = document.querySelector('#submit')
// const comments = document.querySelector('#comment-box')
const titleText = document.getElementById('title')
const comments = document.getElementById('comment-box')
let title_arr = [];
let comments_arr = [];
title.onfocus = function(){
this.setAttribute('placeholder', '')
}
title.onblur = function(){
this.setAttribute('placeholder', textBackUp)
}
field.onfocus = function(){
this.setAttribute('placeholder','')
this.style.borderColor = '#333'
btn.style.display = 'block'
} // when clicking on this, placeholder changes into ' ', border colour changes and buttons will appear.
field.onblur = function(){
this.setAttribute('placeholder',backUp)
} //click away, placeholder returns
const display_comments = () => {
let list = '<ul>'
title_arr.forEach(title => {
comments_arr.forEach(comment => {
list += `<li>${title} <br>${comment}`
})
})
list += '</ul>'
comments.innerHTML = list
}
clear.onclick = function(e){
e.preventDefault();
btn.style.display = 'none'
title.value = ''
field.value = ''
display_comments()
}
submit.onclick = function(e){
e.preventDefault();
const head = title.value;
const content = field.value;
if(head.length > 0){
title_arr.push(head)
display_comments();
title.value = '';
}
if(content.length > 0){
comments_arr.push(content)
display_comments();
field.value = '';
}
}
any help would be appreciated
The problem is that you have a double nested loop, producing a Cartesion product of the all the introduced titles and the comments.
To solve this, use only one array for collecting the input, so that title and comment are always kept together in one array entry. Such an entry can be an object with two properties, one for the title, and one for the comment.
Here is your code adapted, just for fixing that issue:
const title = document.querySelector('#title')
const field = document.querySelector('textarea');
const textBackUp = title.getAttribute('placeholder')
const backUp = field.getAttribute('placeholder')
const btn = document.querySelector('.btn');
const clear = document.getElementById('clear')
const submit = document.querySelector('#submit')
// const comments = document.querySelector('#comment-box')
const titleText = document.getElementById('title')
const comments = document.getElementById('comment-box')
let arr = []; // Only one array
title.onfocus = function(){
this.setAttribute('placeholder', '');
}
title.onblur = function(){
this.setAttribute('placeholder', textBackUp);
}
field.onfocus = function(){
this.setAttribute('placeholder','');
this.style.borderColor = '#333';
btn.style.display = 'block';
}
field.onblur = function(){
this.setAttribute('placeholder', backUp);
}
const display_comments = () => {
let list = '<ul>';
// Only one loop -- over objects with two properties
arr.forEach(({head, content}) => {
list += `<li><b>${head}</b><br>${content}`;
})
list += '</ul>';
comments.innerHTML = list;
}
clear.onclick = function(e){
e.preventDefault();
btn.style.display = 'none';
title.value = '';
field.value = '';
display_comments();
}
submit.onclick = function(e){
e.preventDefault();
const head = title.value;
const content = field.value;
// Only one if-block
if(head.length > 0 || content.length > 0){
arr.push({head, content}); // Only one push -- of an object
display_comments();
title.value = '';
field.value = '';
}
}
<div class="container">
<h1>Write New Post</h1>
<form>
<input id="title" type="text" placeholder="Title" value="">
<textarea id="" placeholder="Leave us a comment" value=""></textarea>
<div class="btn">
<input id="submit" type="submit" value="comment">
<button id="clear">Cancel</button>
</div>
</form>
</div>
<div class="comments">
<h2>Comments</h2>
<div id="comment-box" value="submit">
</div>
</div>

Why I cannot add new note after editing created one?

I cannot add new Note after editing. How can I exit from the cycle?
This is a part where I create a new note
const createNote = () => {
if (button.className === "button") {
const div = document.createElement("div");
div.setAttribute("class", "note");
div.textContent = input.value;
field.appendChild(div);
const btn = document.createElement("button");
btn.setAttribute("class", "edit");
btn.textContent = "Edit";
div.appendChild(btn);
const del = document.createElement("button");
del.setAttribute("class", "del");
del.textContent = "Delete";
div.appendChild(del);
console.log("Note has been created");
input.value = "";
}
Here is a part where I want to edit created Note but also I want to create a new one (this part is inside function createNote)
const edit = document.querySelectorAll(".edit");
for (let i of edit) {
i.onclick = () => {
input.value = i.previousSibling.nodeValue;
button.innerText = "Edit";
button.classList.add("editable");
/*button.classList.remove("button");*/
if (button.className === "button editable") {
button.onclick = () => {
i.previousSibling.nodeValue = input.value;
input.value = "";
button.classList.remove("editable");
button.classList.add("button");
button.innerText = "Add";
};
}
};
}
};
button.onclick = createNote;
Here is HTML that I am using
<body>
<div class="container">
<div class="insert">
<input type="text" name="Note" id="noteId" placeholder="add note">
<button class="button">Add</button>
</div>
<div class="field">
<div class="note">Test note
<button class="edit">Edit</button>
<button class="del">Delete</button>
</div>
</div>
</div>
<script src="js/index.js"></script>
</body>

Changing image while clicking button in html/javascript

Please i want to change the temperature level in each button click. In a way to have a white arrow in a first time, two white arrow i a seconde time .... i have images withe 1 arrow, 2 arrow ext.
this my image in html :
<div id="WBR"><img src="assets/AWImages/V0.png"></div>
<button id= "HI" class="circle" >+</button>
I simulate the button click in javascript like this :
let addb = document.querySelector('#HI');
addb.addEventListener('click', () =>{
input.value = parseInt(input.value)+1;
if((input.value)<5)
{
socket.emit('Value of hum changed',input.value);
}
else
{
input.value =4;
}
});
I really appreciate ur help ;)
let addb = document.querySelector('#WBR');
let wbr = document.querySelector('#HI');
var f = document.querySelector('#f');
var Score = 0;
var win = 5;
var gameOver = false;
addb.addEventListener("click", function () {
if (!gameOver) {
Score++ ;
if (Score == win) {
gameOver = true;
addb.style.color = "green";
}
f.innerHTML = Score;
}
});
<div id="WBR"><img src="assets/AWImages/V0.png"></div>
<button id= "HI" class="circle" >+</button>
<p id="f">0</p>

What is going wrong here?

i made this little script to learn javascript. but i keep getting unexpected token switch..
but hoe do is set switch the corect way??
html:
<p id="new">test<p>
<input id="button" type="submit" name="button" value="enter" />
js:
var switch = true;
if (switch == false){
document.getElementById('button').onclick = function() {
document.getElementById("new").innerHTML = "Mijn Naam!";
var switch = true;
};
} else {
document.getElementById('button').onclick = function() {
document.getElementById("new").innerHTML = "shiva";
var switch = false;
};
}
how about:
<p id="new">test<p>
<input id="button" type="submit" name="button" value="enter" />
var clicked = false;
document.getElementById('button').onclick = function() {
document.getElementById("new").innerHTML = clicked ? "shiva" : "Mijn Naam!";
clicked = !clicked;
};
switch is a reserved word. You should use some variable name else.
By the way, your code is possible to be compressed as follows:
var switchOn = true;
document.getElementById('button').onclick = function() {
document.getElementById("new").innerHTML =
switchOn ? "shiva" :"Mijn Naam!";
switchOn = !switchOn;
}

Categories

Resources