On click get button values from array javascript? - 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>

Related

JavaScript I have to click twice to select to element

Please anyone can help to fix the issue with my code, sometimes I have to click twice to select the next elements
var varientbtn = document.getElementsByClassName('clickthisbtn');
for(let i = 0; i < varientbtn.length; i++) {
varientbtn[i].onclick = function () {
const rbs = document.querySelectorAll('input[name="choice"]');
let selectedValue;
let varientSelectedPrice;
for (const rb of rbs) {
if (rb.checked) {
selectedValue = rb.value;
varientSelectedPrice = rb.getAttribute("data-price");
break;
}
}
document.getElementById('log').innerHTML = selectedValue;
document.getElementById('varientprice').innerHTML = varientSelectedPrice;
console.log(selectedValue, varientSelectedPrice);
}
}
Live preview:
https://codepen.io/Elkazi/pen/wvJeErg
That's because when one of labels be clicked, the checked value of related radio still not change.
Try this
const rbs = document.querySelectorAll('input[name="choice"]');
for(let i = 0; i < rbs.length; i++) {
rbs[i].addEventListener('change', function () {
let selectedValue;
let varientSelectedPrice;
for (const rb of rbs) {
if (rb.checked) {
selectedValue = rb.value;
varientSelectedPrice = rb.getAttribute("data-price");
break;
}
}
document.getElementById('log').innerHTML = selectedValue;
document.getElementById('varientprice').innerHTML = varientSelectedPrice;
console.log(selectedValue, varientSelectedPrice);
});
}
rbs[0].dispatchEvent(new Event('change'));
Since you are adding event listener to the label element, you should make use of its for attribute to get the related input field. That way you don't have to run a loop for all inputs and will always get the latest/correct value.
this will point to the element on which the event handler is called.
var varientbtn = document.getElementsByClassName('clickthisbtn');
for(let i = 0; i < varientbtn.length; i++) {
varientbtn[i].onclick = function () {
let relatedInput = document.getElementById(this.getAttribute("for"));
let selectedValue = relatedInput.value;
let varientSelectedPrice = relatedInput.getAttribute("data-price");;
document.getElementById('log').innerHTML = selectedValue;
document.getElementById('varientprice').innerHTML = varientSelectedPrice;
console.log(selectedValue, varientSelectedPrice);
}
}

onclick toggle between various text

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>

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>

Hide / show buttons with javascript

I have this function which hides some buttons and create another button, when I click on the button created it should make again visible those who were hidden before , but it doesn't really work.
function hideButtons(){
var buttons=document.getElementsByTagName("input");
for(var i=0;i<buttons.length;i++) {
if(buttons[i].type=="button"){
buttons[i].style.display="none";}
}
var back=document.createElement("input");
back.setAttribute("type", "button");
back.setAttribute("value","BACK");
back.setAttribute("id","btnBack");
back.onclick=showButtons();
document.body.appendChild(back);
}
function showButtons(){
var buttons=document.getElementsByTagName("input");
for(var i=0;i<buttons.length;i++) {
buttons[i].style.display="initial";
}
}
You must not call the listener function when you attach the event listener:
function hideButtons () {
var buttons = document.querySelectorAll("input[type=button]");
for (var i = 0; i < buttons.length; i++) {
buttons[i].style.display = "none";
if (buttons[i].getAttribute("id") === "btnBack") {
// remove the id from the current "back" button
buttons[i].removeAttribute("id");
}
}
var back = document.createElement("input");
back.setAttribute("type", "button");
back.setAttribute("value","BACK");
back.setAttribute("id","btnBack");
back.onclick = showButtons; // important!
document.body.appendChild(back);
}
function showButtons () {
var buttons = document.querySelectorAll("input[type=button]");
for (var i = 0; i < buttons.length; i++) {
buttons[i].style.display = "initial";
}
}
Like PeterMader said the problem is that you're calling the showButtons() function in the event listener. You want to call a reference to the function like Peter suggested, or another way is to wrap showButtons() in a function.
function hideButtons() {
var buttons = document.getElementsByTagName("input");
for (var i = 0; i < buttons.length; i++) {
if (buttons[i].type == "button") {
buttons[i].style.display = "none";
}
}
var back = document.createElement("input");
back.setAttribute("type", "button");
back.setAttribute("value", "BACK");
back.setAttribute("id", "btnBack");
back.onclick = function() {
showButtons();
}
document.body.appendChild(back);
}
function showButtons() {
var buttons = document.getElementsByTagName("input");
for (var i = 0; i < buttons.length; i++) {
buttons[i].style.display = "initial";
}
}
hideButtons();
<input type="button">
<input type="button">
<input type="button">
<input>

Javascript - onclick event is not working

So I have this piece of code:
window.onload = function () {make_buttons ('calc'); }
function make_buttons (id) {
console.log (id);
var input = document.createElement("INPUT");
document.getElementById(id).appendChild(input);
for (var i = 0;i < 10; i++){
var btn = document.createElement ("BUTTON");
var t = document.createTextNode (i);
btn.appendChild(t);
document.getElementById(id).appendChild(btn).onclick=document.getElementsByTagName("INPUT").value=i;
}
};
Now when I have created the button with the for loop, it should also have the onclick event attached to it which writes the current value of i into my input form.
Code I have written produces no errors but when the button is clicked, it simply does not do anything. Why is that?
New version:
window.onload = function () {make_buttons ('calc'); }
function make_buttons (id) {
var input = document.createElement("input");
input.type = 'text';
input.id = 'inp';
document.getElementById(id).appendChild(input);
for (var i = 0;i < 10; i++){
var btn = document.createElement ("button");
btn.id = i;
var txt = document.createTextNode (i);
btn.appendChild(txt);
var make_btn = document.getElementById(id).appendChild(btn);
make_btn.onclick = button_pressed (i);
}
};
function button_pressed (id) {
document.getElementById("inp").value += id;
};
Method document.getElementsByTagName() returns a NodeList collection that you should iterate through.
You need to go in loop through retrieved elements and assign the value attribute to each of them.
So that you can change
document.getElementById(id).appendChild(btn).onclick=document.getElementsByTagName("INPUT").value=i;
to something like this:
var id = 'my-form',
btn = document.createElement('input');
btn.type = 'button';
btn.value = 'Click me!';
btn.onclick = function() {
var inputs = document.getElementsByTagName('input');
// NodeList to Array if needed:
// var inputsArray = Array.prototype.slice.call(inputs);
for(var i = 0, l = inputs.length; i < l; i++) {
inputs[i].value = i;
}
return false;
};
document.getElementById(id).appendChild(btn);
DEMO #1
Update:
About your second question, yes it won't work in this way since at the time when your onclick event handler is called it's using the last value assigned to i variable. To avoid this you can just use closures.
For example,
HTML:
<form action="" id="my-form">
<input type="text" id="inp" />
</form>
JavaScript:
var btn,
input,
form,
createHandler;
input = document.getElementById('inp');
form = document.getElementById('my-form');
createHandler = function(i) {
return function() {
input.value += i;
};
};
for(var i = 0; i < 5; i++) {
btn = document.createElement('input');
btn.type = 'button';
btn.value = 'Append ' + i;
form.appendChild(btn);
btn.onclick = createHandler(i);
}
DEMO #2
Also you can use just immediately invoked anonymous function to create that closure in the body of your loop:
for(var i = 0; i < 5; i++) {
// ...
btn.onclick = (function(theNumberToAppend) {
return function() {
input.value += theNumberToAppend;
};
})(i);
}
DEMO #3

Categories

Resources