Hide / show buttons with javascript - 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>

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>

Unable to edit input field added via javascript

I have a simple table with cells. When the user clicks on a cell, a textbox is added inside the cell where they can edit the content. However, when i double click a cell to edit it's content, the attributes of the input field show up. It does not allow me to edit and add another value. Here is the script I'm using.
window.onload = function() {
var cells = document.getElementsByTagName("td");
var theads = document.getElementsByTagName("th");
for (let i = 0; i < cells.length; i++) {
cells[i].addEventListener("click", function() {
highlightCell(i);
});
}
function highlightCell(x) {
var txtBox = document.createElement("input");
txtBox.id = "myTxt";
txtBox.type = "text";
for (var i = 0; i<9; i++) {
if (i == x) {
txtBox.value = cells[i].innerHTML;
cells[i].innerHTML = "";
cells[i].appendChild(txtBox);
cells[i].style.backgroundColor = "lightBlue";
}
}
}
}
Found the solution, just needed to use select(). This highlights the selected field, adds a input box which the user can update, then save the value in the cell when enter is pressed.
function highlightCell(x) {
//add input field inside cell
var txtBox = document.createElement("input");
txtBox.id = x;
txtBox.type = "text";
for (var i = 0; i<9; i++) {
if (i == x) {
txtBox.value = cells[i].innerHTML;
cells[i].innerHTML = "";
cells[i].appendChild(txtBox);
txtBox.select();
cells[i].style.backgroundColor = "lightBlue";
cells[x].onkeypress = function(){
var event = window.event;
var btnPress = event.keyCode;
if(btnPress == 13)
{
var elem = document.getElementById(x);
cells[x].innerHTML = elem.value;
elem.parentNode.removeChild(elem);
}
}
} else {
cells[i].style.backgroundColor = "white";
}
}
}

Stop output printing multiple times if function activated more than once

I'm activating a javascript function with a Jquery onclick button:
$('#on').click(function() {
var a = document.getElementsByTagName('a');
for (i = 0; i < a.length; i++) {
a[i].addEventListener('click', function() {
var span = document.createElement('span');
var text = document.createTextNode(this.innerHTML + " ");
span.appendChild(text);
document.getElementsByClassName('output')[0].appendChild(span);
})
}
});
The problem is if the button is clicked more than once the function will repeat more than once. In this case it will print the output multiple times. How can I modify the javascript function to only print one character per click?
Example:
http://jsfiddle.net/874Ljaq1/
Use the jQuery event binding method one
$('#on').one("click", function() {
var a = document.getElementsByTagName('a');
for (i = 0; i < a.length; i++) {
a[i].addEventListener('click', function() {
var span = document.createElement('span');
var text = document.createTextNode(this.innerHTML + " ");
span.appendChild(text);
document.getElementsByClassName('output')[0].appendChild(span);
})
}
});
You can use the jQuery .data() function to set a flag when the button has been clicked once, and only proceed if the flag is not set.
The code:
$('#on').click(function () {
// if we have a flag that indicates this button has been clicked before,
// don't do anything.
if ($(this).data('clicked'))
return;
$(this).data('clicked', true); // set the flag
var a = document.getElementsByTagName('a');
for (i = 0; i < a.length; i++) {
a[i].addEventListener('click', function () {
var span = document.createElement('span');
var text = document.createTextNode(this.innerHTML + " ");
span.appendChild(text);
document.getElementsByClassName('output')[0].appendChild(span);
})
}
});

How to get out of onmousemove event?

I am dynamically creating a table, with a set number of rows and columns. Once you fire the onmousedown event, it will run a loop to find out which <td></td> you pressed and are moving over, and set it's background color to red.
JSFiddle
I just don't understand how to stop the background color changing once you have fired the onmouseup event.
This is the code part that I am stuck on:
function mousedown() {
var elements = document.querySelector('table').getElementsByTagName('td');
for (var i = 0; i < elements.length; i++) {
elements[i].onmousemove = function() {
this.style.background = "red";
}
elements[i].onmouseup = function() {
this.style.background = "none";
};
}
}
Simply use a flag:
var flag = false;
function mousedown() {
flag = true;
var elements = document.querySelector('table').getElementsByTagName('td');
for (var i = 0; i < elements.length; i++) {
elements[i].onmousemove = function() {
if (flag) this.style.background = "red";
}
elements[i].onmouseup = function() {
flag = false;
};
}
}
JSFiddle here.
I added:
function mouseup() {
var elements = document.querySelector('table').getElementsByTagName('td');
for (var i = 0; i < elements.length; i++) {
elements[i].onmousemove = null;
}
}
and
table.onmouseup = mouseup;
Slightly different approach: http://jsfiddle.net/QYg28/
(function() {
var body = document.querySelector('body');
var table = document.createElement('table');
function createTable(rows, columns) {
var tr;
var td;
for (var i = 0; i < rows; i++) {
tr = document.createElement('tr');
table.appendChild(tr);
for (var j = 0; j < columns; j++) {
td = document.createElement('td');
td.onmouseover = function(){
if(mouseDown)
this.style.background = "red";
}
tr.appendChild(td);
}
}
body.appendChild(table);
}
mouseDown = false;
function mousedown() {
mouseDown = true;
}
function mouseup(){
mouseDown = false;
}
window.onload = createTable(25, 25);
table.onmousedown = mousedown;
table.onmouseup = mouseup;
})();

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