onclick toggle between various text - javascript

I want to toggle between multiple text when i click button.I have created a solution but i would to see a better solution and at end of last click event function i want it to continue to start from beginning.
var qarray = ['canada', 'india', 'america']
var btn = document.querySelector('button');
btn.style.background = 'green';
btn.style.fontSize = '25px';
btn.style.color = 'white';
btn.addEventListener('click', function quotes() {
var textselect = document.querySelector('h2');
var one = textselect.textContent = qarray[0];
btn.addEventListener('click', function quoteone() {
var two = textselect.textContent = qarray[1];
btn.addEventListener('click', function() {
var three = textselect.textContent = qarray[2];
})
})
})
<h2>Shows 3 Country onclick</h2>
<button>Change</button>

When you define a new event listener, you're not removing the old one. So eventually all the listeners run, and they keep adding more each time you click.
Just use a single event listener that uses a global variable to hold the current array index.
var qarray = ['canada', 'india', 'america'];
var qindex = 0;
var btn = document.querySelector('button');
btn.style.background = 'green';
btn.style.fontSize = '25px';
btn.style.color = 'white';
btn.addEventListener('click', function quotes() {
var textselect = document.querySelector('h2');
textselect.textContent = qarray[qindex];
qindex = (qindex + 1) % qarray.length;
})
<h2>Shows 3 Country onclick</h2>
<button>Change</button>
The modulus operator is used to make the index wrap around to 0 when you reach the end of the array.

var qarray = ['canada', 'india', 'america']
var btn = document.querySelector('button');
btn.style.background = 'green';
btn.style.fontSize = '25px';
btn.style.color = 'white';
var countClick =0;
btn.addEventListener('click', function quotes() {
var textselect = document.querySelector('h2');
if(qarray.length > countClick) {
textselect.textContent = qarray[countClick];
countClick++;
} else {
countClick =0;
textselect.textContent = qarray[countClick];
}
})
<h2>Shows 3 Country onclick</h2>
<button>Change</button>

Related

On click get button values from array javascript?

I have a function that creates a button for each value in an array. I want to get the value of the button that is clicked and store it in a variable.
dates_button = ['8/21/2020','8/28/2020','9/4/2020','9/11/2020','9/18/2020','9/25/2020','10/16/2020','11/19/2020','1/14/2021','3/19/2021','6/18/2021','9/17/2021','1/20/2022']
function printBtn() {
for (var i = 0; i < dates_button.length; i++) {
var btn = document.createElement("button");
var t = document.createTextNode(dates_button[i]);
btn.appendChild(t);
document.body.appendChild(btn);
}
}
printBtn();
You can add an event handler that reads back the textContent from the button; then you can do what you want with it in the event handler. For example:
dates_button = ['8/21/2020', '8/28/2020', '9/4/2020', '9/11/2020', '9/18/2020', '9/25/2020', '10/16/2020', '11/19/2020', '1/14/2021', '3/19/2021', '6/18/2021', '9/17/2021', '1/20/2022']
function btnClick(e) {
let date = e.target.textContent;
// do something with it
console.log(date);
}
function printBtn() {
for (var i = 0; i < dates_button.length; i++) {
var btn = document.createElement("button");
var t = document.createTextNode(dates_button[i]);
btn.appendChild(t);
btn.onclick = btnClick;
document.body.appendChild(btn);
}
}
printBtn();
const dates_button = ['8/21/2020', '8/28/2020', '9/4/2020', '9/11/2020', '9/18/2020', '9/25/2020', '10/16/2020', '11/19/2020', '1/14/2021', '3/19/2021', '6/18/2021', '9/17/2021', '1/20/2022']
function printBtn() {
for (let i = 0; i < dates_button.length; i++) {
let btn = document.createElement("button");
let t = document.createTextNode(dates_button[i]);
btn.appendChild(t);
document.body.appendChild(btn);
btn.addEventListener('click', () => {
alert(dates_button[i]);
});
}
}
printBtn();
You don't even need to read the text out of the DOM if you just add the event listener in your loop there.
Or, if you prefer, this might be a little more efficient because it only requires one event listener.
const dates_button = ['8/21/2020', '8/28/2020', '9/4/2020', '9/11/2020', '9/18/2020', '9/25/2020', '10/16/2020', '11/19/2020', '1/14/2021', '3/19/2021', '6/18/2021', '9/17/2021', '1/20/2022']
function printBtn() {
for (let i = 0; i < dates_button.length; i++) {
let btn = document.createElement("button");
let t = document.createTextNode(dates_button[i]);
btn.appendChild(t);
document.body.appendChild(btn);
}
}
document.addEventListener('click', (ev) => {
if (ev.target.matches('button')) {
console.log(ev.target.innerText);
}
});
printBtn();
Add a value property on your button and attach an event listener. Then onClick's event you can access the value as event.target.value.
dates_button = [
"8/21/2020",
"8/28/2020",
"9/4/2020",
"9/11/2020",
"9/18/2020",
"9/25/2020",
"10/16/2020",
"11/19/2020",
"1/14/2021",
"3/19/2021",
"6/18/2021",
"9/17/2021",
"1/20/2022"
];
function printBtn() {
for (var i = 0; i < dates_button.length; i++) {
var btn = document.createElement("button");
var t = document.createTextNode(dates_button[i]);
btn.appendChild(t);
document.body.appendChild(btn);
btn.addEventListener("click", handleClick);
btn.value = dates_button[i];
}
}
function handleClick(event) {
console.log(event.target.value);
}
printBtn();
You could simply use forEach function and use onClick function to get the value of a clicked date.
Live Demo:
let dates_button = ['8/21/2020', '8/28/2020', '9/4/2020', '9/11/2020', '9/18/2020', '9/25/2020', '10/16/2020', '11/19/2020', '1/14/2021', '3/19/2021', '6/18/2021', '9/17/2021', '1/20/2022']
function printBtn() {
dates_button.forEach(function(date) {
var btn = document.createElement("button");
var text = document.createTextNode(date);
btn.appendChild(text);
btn.value = date;
btn.onclick = function() {
console.log(this.value)
}
document.querySelector('#el').appendChild(btn); //append all buttons
})
}
printBtn();
<div id="el"></div>

JavaScript: Conditioned button creation and removal

I have to solve a problem which sounds like this:
I have a HTML file with:
1 input
1 select with no value
1 button - 'Start'
After pressing the Start button, new buttons will be created from 3 to 3 seconds, with the names and ids 'B1', 'B2', 'B3', until reaching the value entered in the input.
Clicking on a button so created, it will disappear, and its id will appear as an option in select.
This is what I have done until now, but I don't know how to continue..
window.onload
{
document.getElementsByTagName("button")[0].onclick = function ()
{
if(document.getElementsByTagName("input")[0].value > 0)
{
var i=1;
var n = document.getElementsByTagName("input")[0].value;
var addButtons = setInterval(function()
{
if(i==n) clearInterval(addButtons);
var button = document.createElement("BUTTON");
button.setAttribute("id", "b"+i);
document.body.appendChild(button);
i=i+1;
}, 3000);
}
};
}
1- Instead of using document.getElementsByTagName use document.querySelectorAll because of perfomance issues.
2- Define this event listener for each new button
button.addEventListener('click', function(e) {
e.target.style.display = 'none';
var option = document.createElement('option');
option.innerHTML = e.target.name;
document.querySelectorAll("select")[0].append(option)
});
Full code
document.getElementsByTagName("button")[0].onclick = function() {
if (document.getElementsByTagName("input")[0].value > 0) {
var i = 1;
var n = document.getElementsByTagName("input")[0].value;
var addButtons = setInterval(function() {
if (i == n) clearInterval(addButtons);
var button = document.createElement("BUTTON");
button.setAttribute("id", "b" + i);
button.setAttribute("name", "b" + i);
button.innerHTML = "B" + i;
button.addEventListener('click', function(e) {
e.target.style.display = 'none';
var option = document.createElement('option');
option.innerHTML = e.target.name;
document.querySelectorAll("select")[0].append(option)
});
document.body.appendChild(button);
i = i + 1;
}, 3000);
}
};
<button>Click me</button>
<input type="number" />
<select></select>

document.getElementById class applies to the whole array instead of each element

<p><span id="sr" class="btn">elements of the array</span></p>
for(var i = 0; i < myarray.length; i++)
{
var sr = (function(val) {
btn = document.createElement('button');
btn.data = val;
btn.innerHTML = val;
btn.addEventListener('click', checkAnswer);
document.body.appendChild(btn);
return btn.data = val;
})//(myarray[i]);
document.getElementById("sr").innerHTML = myarray;
}
With this code the elements of the array appear in the html span. I want each element to appear as a button, as defined in the class "btn". However, the class changes the style of the array as a whole, not as single buttons. What is the correct way to define the style of each button?
I tried document.getElementById("sr").innerHTML = myarray.class="btn";. It does not work. Definitely not the correct syntax. Any idea?
Is this what you want to achieve?
let container = document.getElementById('sr');
let array = ['element1', 'element2', 'element3'];
function checkAnswer () {
console.log('Selected answer: ', this.textContent);
}
for (let i = 0; i < array.length; i++) {
let button = document.createElement('button');
button.textContent = array[i];
button.addEventListener('click', checkAnswer);
container.appendChild(button);
}
<p><span id="sr" class="btn"></span></p>
If I understand you correctly, you want to add btn class to your dynamically created buttons with myarray elements.
What is the correct way to define the style of each button?
I tried document.getElementById("sr").innerHTML = myarray.class="btn";
You can use element.classList.add('your-class');
var myarray = ["Array", "elements"]; //let's say
for (var i = 0; i < myarray.length; i++) {
var sr = (function(val) {
btn = document.createElement('button');
btn.data = val;
btn.innerHTML = val;
btn.classList.add("btn")
btn.addEventListener('click', checkAnswer);
document.body.appendChild(btn);
return btn.data = val;
})(myarray[i]);
//document.getElementById("sr").innerHTML = myarray;//I don't know why this line here?
}
function checkAnswer(e){
}
Use Element.dataset instead of creating a .data property. Pass i to IIFE. If you are trying to display the array myarray as .innerHTML of #sr, concatenate "[" to beginning and "]" to end of myarray setting at .innerHTML, as .innerHTML casts Array to String.
If you are trying to append created element to #sr, do not append element to document.body, but #sr.
function checkAnswer() {
console.log(this.dataset.value)
}
var myarray = [1, 2, 3];
for (var i = 0; i < myarray.length; i++) {
(function(val) {
var btn = document.createElement('button');
btn.dataset.value = val;
btn.className = "btn"; // set `btn` `.className` to `"btn"`
btn.innerHTML = val;
btn.addEventListener('click', checkAnswer);
document.body.appendChild(btn);
// document.getElementById("sr").appendChild(btn);
})(i);
}
document.getElementById("sr").innerHTML = "[" + myarray + "]";
<p><span id="sr" class="btn">elements of the array</span></p>

How to remove an item in an array using an onclick function?

In this code, I am trying to push items into the array and then removing them.
If you see below, the create button will give me a blank input and a button that stores it into an array. After it is pushed into the array, the view button goes through the array and displays all the items with the buttons "edit" and "delete" beside it. This is where my problem lies... for each item that is put into the array, it displays it on the Html and has its own buttons. How do I delete that item from the array when I click on a specific delete button?
//variables
var create = document.getElementById("create");
var view = document.getElementById("view");
var display = document.getElementById("display");
var text = document.getElementById("text");
var push = document.getElementById("push");
var arr1 = [];
//create button
create.onclick = function () {
text.style.display = "inline";
push.style.display = "inline";
}
//push button
push.onclick = function () {
arr1.push(text.value);
push.dataset.u_index;
console.log(arr1);
text.value = "";
}
//view button
view.onclick = function () {
for (var i = 0; i < arr1.length; i++) {
var disp = document.createElement("div");
disp.innerHTML = arr1[i];
display.appendChild(disp);
var edit = document.createElement("button");
var edit_t = document.createTextNode("Edit");
disp.appendChild(edit);
edit.appendChild(edit_t);
var del = document.createElement("button");
var del_t = document.createTextNode("Delete");
disp.appendChild(edit);
edit.appendChild(edit_t);
disp.appendChild(del);
del.appendChild(del_t);
}
//del button
del.onclick = function () {
}
}
}
You need some way of identifying the element you want to delete so it can be tied to the delete function. Here's some code that shows one possible way using data attributes.
//variables
var create = document.getElementById("create");
var view = document.getElementById("view");
var display = document.getElementById("display");
var text = document.getElementById("text");
var push = document.getElementById("push");
var results = document.getElementById("results");
var arr1 = [];
//create button
create.onclick = function() {
text.style.display = "inline";
push.style.display = "inline";
}
//push button
push.onclick = function() {
arr1.push(text.value);
push.dataset.u_index;
console.log(arr1);
text.value = "";
}
//view button
view.onclick = function() {
for (var i = 0; i < arr1.length; i++) {
var disp = document.createElement("div");
disp.innerHTML = arr1[i];
results.appendChild(disp);
var edit = document.createElement("button");
var edit_t = document.createTextNode("Edit");
disp.appendChild(edit);
edit.appendChild(edit_t);
var del = document.createElement("button");
var del_t = document.createTextNode("Delete");
disp.appendChild(edit);
edit.appendChild(edit_t);
disp.appendChild(del);
del.appendChild(del_t);
del.setAttribute('data-item-index', i);
//set onclick fn for del button
del.onclick = function() {
var itemIndex = this.getAttribute('data-item-index');
arr1.splice(itemIndex, 1);
console.log(arr1);
results.innerHTML = '';
view.click();
};
}
}
<div id='display'>
<button id="create">Create</button>
<div>
<input type="text" id='text'>
<button id='push'>Push</button>
</div>
<button id='view'>View</button>
<div id='results'></div>
</div>

Replace header text with button text using JavaScript

I am using only JavaScript to create buttons and need to add click handlers to the buttons that will replace the header with the contents of the buttons. I have been trying to figure out how to do this for a while. Any help would be great! Thank you!
Below is my JavaScript code that creates the buttons and header.
var col = document.createElement('div');
col.className = 'col';
document.body.appendChild(col);
var header = document.getElementById('col');
var h = document.createElement("H3");
h.innerHTML = "Nothing clicked yet!";
col.appendChild(h);
var divOne = document.createElement('div');
col.appendChild(divOne);
var btnOne = document.getElementById('col');
var textOne = ["1", "2", "3", "4"];
textOne.forEach(function(post) {
var postDiv = document.createElement("div");
postDiv.className = 'btn btn-default';
postDiv.innerHTML = post;
col.appendChild(postDiv);
});
Add an event to your button elements, but as other answers pointed out, a good practice is to assign IDs to your elements for more accurate lookup :
var btnOne = document.getElementById('col');
var textOne = ["Left", "Middle", "Right"];
textOne.forEach(function(post) {
var btnGroupFour = document.createElement('button');
btnGroupFour.className = 'btn btn-default';
btnGroupFour.innerHTML = post;
btnGroupFour.addEventListener("click", function() {
var header = document.getElementsByTagName('H3')[0];
header.innerHTML = this.innerHTML;
}, false);
divThree.appendChild(btnGroupFour);
});
First of all, you are not creating buttons, you're creating divs, although you're using the button classes from bootstrap (I gues...).
Anyway, the way to proceed would be to add a onclick attribute with a callback function, witch takes one argument: the event itself. Then, with the target attribute of the event object, you're getting access to the event source tag and with value you will get the value.
Just like this:
<input type="button" id="button" value="Test Value!" />
<span id="output"></span>
<script>
document.getElementById("button").addEventListener('click', callback);
function callback(e) { document.getElementById("output").innerHTML = e.target.value; }
</script>
Just assign an ID for your header, and while creating the buttons in the loop. Just assign the onclick callback of the button, to get the id of the header, and replace the text
textOne.forEach(function(post) {
var btnGroupFour = document.createElement('button');
btnGroupFour.className = 'btn btn-default';
btnGroupFour.innerHTML = post;
btnGroupFour.onclick = function(){document.getElementById('headerID').innerHTML = post} ;
h.appendChild(btnGroupFour);
});
Should Work for your situation.
A short Demo
Fairly simple, just add an eventListener onto the element during creation. All I really had to add to your code was: .addEventListener("click", function(){ h.innerHTML = post;});
http://www.w3schools.com/jsref/met_element_addeventlistener.asp
<!DOCTYPE html>
<html>
<body>
<p>Hover over the checkbox to simulate a mouse-click.</p>
<script>
var divContainer = document.createElement('div');
divContainer.className = 'container';
document.body.appendChild(divContainer);
var row = document.createElement('div');
row.className = 'row';
divContainer.appendChild(row);
var col = document.createElement('div');
col.id = 'col-md-12';
row.appendChild(col);
var header = document.getElementById('col');
var h = document.createElement("H3");
h.innerHTML = "Nothing clicked yet!";
col.appendChild(h);
var star = document.createElement('div');
col.appendChild(star);
var btnStar = document.getElementById('col');
var textStar = ["Star"];
textStar.forEach(function(post) {
var postStar = document.createElement("div");
postStar.className = 'btn btn-default';
postStar.innerHTML = post;
postStar.addEventListener("click", function(){
h.innerHTML = post;});
col.appendChild(postStar);
});
var secondLine = document.createElement("HR");
document.body.appendChild(secondLine);
col.appendChild(secondLine);
var divOne = document.createElement('div');
col.appendChild(divOne);
var btnOne = document.getElementById('col');
var textOne = ["1", "2", "3", "4"];
textOne.forEach(function(post) {
var postDiv = document.createElement("div");
postDiv.className = 'btn btn-default';
postDiv.innerHTML = post;
postDiv.addEventListener("click", function(){
h.innerHTML = post;});
col.appendChild(postDiv);
});
var btnTwo = document.getElementById('col');
var textTwo = ["5", "6", "7", "8"];
textTwo.forEach(function(post) {
var btnGroupFour = document.createElement('button');
btnGroupFour.className = 'btn btn-default';
btnGroupFour.innerHTML = post;
btnGroupFour.addEventListener("click", function(){
h.innerHTML = post;});
col.appendChild(btnGroupFour);
});
var secondLine = document.createElement("HR");
document.body.appendChild(secondLine);
col.appendChild(secondLine);
var divThree = document.createElement('div');
col.appendChild(divThree);
var btnOne = document.getElementById('col');
var textOne = ["Left", "Middle", "Right"];
textOne.forEach(function(post) {
var btnGroupFour = document.createElement('button');
btnGroupFour.className = 'btn btn-default';
btnGroupFour.innerHTML = post;
btnGroupFour.addEventListener("click", function(){
h.innerHTML = post;});
divThree.appendChild(btnGroupFour);
});
</script>
</body>
</html>

Categories

Resources