Is there a way for buttons to display multiple texts? - javascript

I have this idea where if you press a button, it'll display a text, but not only one text, but multiple, just not at once. If you press the button again, it'll display another text after it. So far, I'm only limited to only one text being displayed. I'm not really sure how to go from what I'm trying to achieve. I had an idea about using arrays but arrays and buttons didn't seem to work all that great, at least for me. I might have done something wrong for it to not work. Anyways, the idea was that the button would call from the array each time you'd click it so it'd display a different text.
So if you press the button once, it would output: "Hello"
And if you press it again, it would output: "How are you?"
and so on and so forth.
How would I do this in terms of making something like this happen?
Disclaimer: I don't want the text to be replaced with a new text. I want it solely outputted afterwards.
<button id = "age-button" button onClick = "ageButton()">AGE!</button>
<script>
function ageButton() {
var text = "You are born.";
document.getElementById("age1").innerHTML = text;
}
</script>
This code above only displays one text. How would I let it display another text after I press the button again?

// Define array of string that you would like to show on each click
const labels = [
"String 1",
"String 2",
"String 3"
// ... so on (add as many as you like)
];
// lets start from zero index
let currentIndex = 0;
// get the button HTMLElement
const nextBtn = document.querySelector("#next-btn");
const contentsEl = document.querySelector("#contents");
// attach onClick event handler / listner
nextBtn.addEventListener("click", function(event) {
// get the label string to show
const label = labels[currentIndex];
const p = document.createElement("p");
p.textContent = label;
contentsEl.append(p);
// increment the index
currentIndex++;
// set a trap
if (currentIndex === labels.length) {
//(bonus) disable the button when you reach the end
this.disabled = true;
}
});
<button id="next-btn">Show Next</button>
<div id="contents"></div>

Here is an example how you can do that.
let texts = ["You are born", "Hi there", "I'm ready"];
function ageButton() {
let line = texts.shift(); //use shift to get the first element in array
if (line) {
//use += operator to append to previous content
document.getElementById("age1").innerHTML += "<p>" + line + "</p>";
}
}
<button id="age-button" onclick="ageButton()">AGE!</button>
<div id="age1"></div>

Related

onClick Add to Grid from an Array but duplicates on second iteration

Use case is to create Add/show/select/delete text messages on a page. I have used array to store the messages on each click till here it works fine but when I try to create Divs and show the messages in grid, I am having duplication on each click. I can see that my function is reading the array fine and creating the div's on the first click but it does not clear the previously created div on second iteration. Not sure how to approach this. Please advise.
here is the snippet.
<script>
//<!-- Fetch data from Textarea when user Click Save and create or push in an array -->
let ArrNotes = [];
function SaveNote() {
let edittext = document.getElementById("editor").value;
ArrNotes.push(edittext);
document.getElementById("SavedNote").innerHTML = ArrNotes;
let container = document.getElementById("GridNotes");
container.className= "GridNotes";
ArrNotes.forEach(createGrid);
function createGrid(item,index)
{
text = undefined;
var tag = document.createElement("div");
tag.className= "grid";
var text = document.createTextNode(index + ": " + item);
//tag.appendChild(text);
container.appendChild(text);
}
}

Replacing a string value using the click event

I'm building a donate modal.
When I click on the donate button, the progress bar gets incremented based on the input value.
I want to replace the money string from h1 when I click on donate.
So if the input value is 10, when I click on the donate button the h1 should read:
$140 is still needed for this project
This runs only once, because it replaces the text only when it finds '$150'.
.modal
.modal-header-box
h1 $150 is still needed for this project
.modal-content
progress#myProgress(value='50', max='200')
h1 Only days left to fund this project. Join the other 42 other donors who have already suppoorted this project. Every dollar helps.
input(type='number', placeholder='$' id='value', max='100')
button#btn Give Now
.button.save-later Save for later
.button.social Tell your friends
JavaScript
document.getElementById('btn').addEventListener('click', function() {
var x = document.getElementById('myProgress');
console.log(x.value, document.getElementById('value').value)
x.value = +x.value + +document.getElementById('value').value;
let difference = x.max - x.value;
console.log(difference);
document.body.innerHTML = document.body.innerHTML.replace('$150', `${difference}`);
});
Is there any way to make this more dynamic, so the string will update If click on the donate button multiple times?
CodePen link
https://codepen.io/make96/pen/XWZdbPZ
Your problem resides in replacing everything on the page. You should restrict the transformation to the elements that you are changing.
Instead of replacing document.body, then target the modal header box instead.
document.body.innerHTML = document.body.innerHTML.replace('$150', `${difference}`);
Replace the modal-header-box content instead.
document.getElementsByClassName("modal-header-box")[0].innerHTML = `<h1>$${difference} is still needed for this project</h1>`;
Just put the number in a span and only change the span input on every click.
You take the value of the span and the value of the input box and substract it everytime you click on it.
Function:
document.getElementById("btn").onclick = function(){
var value = parseInt(document.getElementById("test").innerHTML);
var donate = parseInt(document.getElementById("value").value);
document.getElementById("myProgress").value += donate;
document.getElementById("test").innerHTML = value-donate;
}
modal-header-box
.modal-header-box
h1 $<span id="test">150</span> is still needed for this project
Don't replace the document body, Not good practice to update the body every time, update only the required field.
Javascript
document.getElementById("btn").addEventListener("click", function() {
const title = document.getElementById("title");
const x = document.getElementById("myProgress");
const prev = +x.value
x.value = prev + +document.getElementById("value").value;
let difference = x.max - x.value;
title.innerHTML = title.innerText.replace(x.max - prev, `${difference}`);
});
Template
h1#title $150 is still needed for this project

How to check if a button was clicked, put a value on it and then use innerHTML?

basically I want to provide the user two options, Yes or No. For example, if he clicks the Yes button, then this information is saved and I can show what he chose at the end of the questionnaire.
I'm trying this way, but it's not working. At the end, nothing appears on the screen...
answer2-A = Yes Button
answer2-B = No Button
----------------------------//------------------------//-------------------------
document.getElementById('answer2-A').addEventListener("click", defineYes);
document.getElementById('answer2-B').addEventListener("click", defineNo);
};
function defineYes(){
document.getElementById('answer2-A').value = 'Yes';
document.getElementById('info').innerHTML = document.getElementById('answer2-A');
};
function defineNo(){
document.getElementById('answer2-B').value = 'No';
document.getElementById('info').innerHTML = document.getElementById('answer2-B');
Few things to address - without seeing the HTML I assume the value property isn't set on the buttons. Additionally you can/should get references to the buttons and re-use them instead of querying over and over. You can use the target of the event to access which button you clicked.
const yesBtn = document.getElementById('answer2-A')
const noBtn = document.getElementById('answer2-B')
const info = document.getElementById('info');
yesBtn.addEventListener("click", trackClick);
noBtn.addEventListener("click", trackClick);
function trackClick(e) {
info.innerHTML = e.target.value;
}
<button id="answer2-A" value="Yes">Yes</button>
<button id="answer2-B" value="No">No</button>
<div id="info"></div>

Still Not Working.. Swapping .innerHTML with .js variable

When the user visits the page, this HTML text must display.
<p id="exampleText">Hit The "Change Text" Button Below To Change <span id="thisText"><strong>This</strong></span> Text and see how the innerHTML property tag works </p>
After clicking this button:
<button id="changeButton" type="button" value="default Text" onclick="textChanger()">Change Text</button>
Display This Text:
var txtExmp1 = "Hooooooooooooraayy!!, You Clicked and Changed The Text..." + "<br><br><br>" + "but now you have to fix me so i can change again";
Now user should be able to click the button and see previous text and back to the "Hooray" message in var txtExmp1.
I've tried to use an if statement but didnt work. Here's the code:
var defaultText = document.getElementById("exampleText");
if (defaultTex.innerHTML === defaultText){
defaultText.innerHTML = txtExmp1;
}
else {
defaultText.innerHTML = defaultText;
}
How can I make this texts toggle between each other considering one is html and the other is javascript. What is the simple and most effective way to toggle this texts?
Heres what it looks like (Screenshot image):
i.Before Click
ii.After click, but wont change again
This is relatively simple, when changing the text you need to take the current visible one and save it in a variable, then show the other stored text you have in txtExmp1 then when the use click again you take the other visible text store it and show the one you stored before, doing it this is highly inefficient.
From the start you store both strings in variables or array then toggle between them.
Of course this is just one way to achieve this.
let text = ["Hooooooooooooraayy!!, You Clicked and Changed The Text... <br><br><br>but now you have to fix me so i can change again", "Hit The Change Text Button Below To Change <span id='thisText '><strong>This</strong></span> Text and see how the innerHTML property tag works "];
let index = 0;
function textChanger() {
// Get the p Element refrence so we can modify it
var pElement = document.getElementById("exampleText");
// text[index] will return one of the texts from the array
// depening on the index if 0 its the first one
// if 1 it's the second one
// that's why we're altering index's value after every change
if (index == 0) {
pElement.innerHTML = text[index];
index = 1;
} else if (index == 1) {
pElement.innerHTML = text[index];
index = 0;
}
}
<p id="exampleText">Hit The Change Text Button Below To Change <span id='thisText '><strong>This</strong></span> Text and see how the innerHTML property tag works </p>
<button id="changeButton" type="button" value="default Text" onclick="textChanger()">Change Text</button>
The word you are searching is toggle. Try switch case:
var theToggle = document.getElementById("changeButton");
var toggleMe = document.getElementById("exampleText");
toggleMe.toggleStatus = "on";
theToggle.onclick = function(){
switch(toggleMe.toggleStatus){
case "on":
toggleMe.toggleStatus="off";
toggleMe.textContent = "Hooooooooooooraayy";
break;
case "off":
toggleMe.toggleStatus="on";
toggleMe.textContent = " Hit The Change Text Button Below To change...";
break;
}
Good luck!

Randomly generate user input

Im really new to coding, and i wanted to know if it was possible to randomly generate entries submitted by a user.
For example.
If the user was to enter 5 words,
Would they then be stored in a way that you would have a button to just click 'next' and randomly move through them.
Ive checked all around but cant seem to find anything,
Please help!!
Thanks
Your question is very abstract but the answer below details the following:
A user is able to save an infinite number of words.
A button is then able to randomly take one of these words and display it on the screen.
preview
https://jsfiddle.net/gwcq2qc9/1/
html
<input id="word"><button id="save">save</button>
<br><br>
<button id="show">show</button><br>
Random: <span id="output">...</span>
javascript
var words = [];
var input = document.getElementById('word');
var saveButton = document.getElementById('save');
var showWordButton = document.getElementById('show');
var output = document.getElementById('output');
saveButton.addEventListener('click', function () {
words.push(input.value);
input.value = '';
}, false);
showWordButton.addEventListener('click', function () {
output.innerHTML = getRandomWord();
})
function getRandomWord () {
return words[Math.floor(Math.random()*words.length)]
}

Categories