How do you dynamically display a button using JavaScript? - javascript

Below I have code where I am trying to dynamically create a button using Javascript (I don't want to just create a button with HTML) When I locally run the web page no button appears.
The buttonActionFunction is a separate function I have (that is fully working) where an image appears when the button is clicked.
Also how do I add to that code so that once the button is clicked that the button deactivates so they can't click it again?
<script>
function buttonFunction() {
var button= document.createElement("button");
button.appendChild(document.createTextNode("Click Me"));
button.onclick=buttonActionFunction();
document.getElementById("divId").appendChild(button);
}
buttonFunction();
</script>

function createButton(context, func) {
var button = document.createElement("input");
button.type = "button";
button.value = "Click Me";
button.onclick = func;
context.appendChild(button);
}
function functienaam()
{
createButton(document.body, functienaam);
}
createButton(document.body, functienaam);
jsfiddle : https://jsfiddle.net/fv42orad/1/

Add <div id="divId"></div> to your html
As for disabling the button on click
function buttonActionFunction(e) {
e.target.disabled = true
}
and button.onclick=buttonActionFunction; not
button.onclick=buttonActionFunction();

Based on #lordKain answer I've updated the code to disable the previous button when it is clicked, as shown bellow:
function createButton(context){
var button = document.createElement("input");
button.type = "button";
button.value = "Click Me";
button.onclick = function() {functienaam(button)};
context.appendChild(button);
}
function functienaam(button)
{
createButton(document.body);
button.disabled = true;
}
createButton(document.body);
https://jsfiddle.net/5unLc5xr/

Related

Button Doesn't Work If Created Using innerHTML

I have this kind of structure
<button ng-click="something(1)">click!</button>
<div id="place"></div>
something() works in this situation, but if I try to make another button with innerHTML on a js code
str="<button ng-click=\"something(2)\">click 2!</button>"
document.getElementById("place").innerHTML = str;
thrn the 2nd button, the one created by innerHTML, apears normal, but doesn't call the function something() when clicked
Is there a nother way to add the button? the buttons should be generated proceduraly as the page runs
Thank you very much!
<script>
let btn = document.createElement("button");
btn.innerText = "click2"
// class
btn.classList = [];
// on click function
btn.onclick = () => {
}
document.getElementById("place").innerHTML = "";
document.getElementById("place").appendChild(btn)
</script>

Why does this javascript function activate at the wrong time?

Here's the code I'm currently using
function firstChildAge() {
var header = document.createElement('H3');
var body = document.getElementsByTagName('BODY');
var textnode = document.createTextNode("WHAT IS THE AGE OF THE FIRST CHILD?");
var inputChildOne = document.createElement("Input");
var childOneAgeResponse = inputChildOne.value;
header.appendChild(textnode);
document.body.appendChild(header);
document.body.appendChild(inputChildOne);
}
function submitButton() {
var btn = document.createElement('Button');
document.body.appendChild(btn);
btn.onClick = testFunction_2();
}
function testFunction_2() {
alert("foo");
}
if (childrenResponse == 1) {
firstChildAge();
submitButton();
}
As you can see, if childrenResponse (the user's response to a previous query) is equal to 1, both functions are activated. The attempted goal is to create a text node, an input, and a button. The button as of right now, should active testFunction2() which alerts us that it is working. But, testFunction2() activates before the text node or input even shows up. I can find the reason for this, and if anyone can help me out I'd greatly appreciate it. Thank you.
Also, on a side note, how can I add text to the button created in submitButton() ? Thanks!
You have called the testFunction_2, instead of assigning it. This should work out fine.
function submitButton() {
var btn = document.createElement('Button');
btn.onclick = testFunction_2;
document.body.appendChild(btn);
}
You are calling the function testFunction_2() in onClick. You need to add event listener to button as shown below
btn.addEventListener('click', testFunction_2);
To add text to button use
var txt = document.createTextNode("CLICK ME");
btn.appendChild(txt);
Check the snippet below
function firstChildAge() {
var header = document.createElement('H3');
var body = document.getElementsByTagName('BODY');
var textnode = document.createTextNode("WHAT IS THE AGE OF THE FIRST CHILD?");
var inputChildOne = document.createElement("Input");
var childOneAgeResponse = inputChildOne.value;
header.appendChild(textnode);
document.body.appendChild(header);
document.body.appendChild(inputChildOne);
}
function submitButton() {
var btn = document.createElement('Button');
var txt = document.createTextNode("CLICK ME");
btn.appendChild(txt);
document.body.appendChild(btn);
btn.addEventListener('click', testFunction_2);
}
function testFunction_2() {
alert("foo");
}
childrenResponse = 1;
if (childrenResponse == 1) {
firstChildAge();
submitButton();
}
You are calling the function testFunction_2 in onClick. You need to provide reference.
That also won't work. You need to add event listener to button.
And for setting the text, just set innerHTML of button.
var btn = document.createElement('Button');
btn.innerHTML = "click";
btn.addEventListener('click', testFunction_2);
document.body.appendChild(btn);
btn.onclick = testFunction_2; // in place of addEventListener.
// if you want to use onclick. use small case 'c' in onclick.
There were 2 problems:
onClick should've been onclick.
You were executing the function and assigning the result of that function to the onclick. btn.onClick = testFunction_2(); should be btn.onClick = testFunction_2;
See working snippet below.
function firstChildAge() {
var header = document.createElement('H3');
var body = document.getElementsByTagName('BODY');
var textnode = document.createTextNode("WHAT IS THE AGE OF THE FIRST CHILD?");
var inputChildOne = document.createElement("Input");
var childOneAgeResponse = inputChildOne.value;
header.appendChild(textnode);
document.body.appendChild(header);
document.body.appendChild(inputChildOne);
}
function testFunction_2() {
alert("foo");
}
function submitButton() {
var btn = document.createElement('button');
btn.innerHTML = "Some button name";
btn.onclick = testFunction_2;
document.body.appendChild(btn);
}
var childrenResponse = 1;
if (childrenResponse == 1) {
firstChildAge();
submitButton();
}
In javascript you can use the innerHTML set the button's HTML contents.
See Setting button text via javascript
btn.innerHTML = "This is a button name";
The Mozilla Developer Network is a good resource. Here's two links for the above mentioned snippets.
MDN innerHTML
MDN HTML Button element

How to click all buttons of a specific class with one button in javascript

The buttons that i want to click with one button.
The following button are created with every file upload so thats why it is buttons.
var td4=row.insertCell(-1);
td4.innerHTML="<a type='button' class='delete-button' href='javascript:void(0)' onclick='Attachment_Remove(this)'><i class='fa fa-trash' aria-hidden='true'></i> delete</a>";
What i want:
I want to have a button created in js and then when i click that button it should click all buttons of the upper class.
What i have tried:
// 1. Create the button
var button = document.createElement("button");
button.setAttribute("onclick", "divFunction()");
function divFunction(){
var a = document.getElementsByClassName('delete-button');
for(var i = 0; i <= a.length; i++)
a[i].click();
}
// 2. Append somewhere
var body = document.getElementsByTagName("body")[0];
body.appendChild(button);
Here is a simple function that does the job:
const addAButtonThatClicksAllButtons = () => {
const button = document.createElement('button');
button.onclick = () =>
Array.from(document.getElementsByClassName('delete-button'))
.forEach(btn => btn.click());
document.body.appendChild(button);
};
It might be cleaner if you use jQuery:
const addAButtonThatClicksAllButtons = () => {
const button = $('<button/>').click(
() => $('delete-button').click()
);
$('body').append(button);
};

Change image of button when pressed, using javascript

I am trying to set a value in variable when a specific button is pressed. I want this button to be in pressed state when i again reload the page. I am trying to check the value of variable in pageloaded function but i don't know that how can change the state of button in javascript. Pls help
HTML:
<button onclick="changeit()"><img src="bla.jpg" id="changevalue"></button>
JS:
function changeit(){
document.getElementById("changevalue").src = "newimg.jpg";
}
HTML:
<button id="myButton"><img src="myImage.jpg" id="myImage"></button>
JS:
var NEW_IMAGE_URI = "myNewImage.jpg";
var buttonState = false;
function changeButtonImage(){
if (buttonState) {
return;
}
document.querySelector("#myImage").src = NEW_IMAGE_URI;
buttonState = true;
}
document.addEventListener("DOMContentLoaded", function(event) {
var buttonElement = document.querySelector('#myButton');
buttonElement.addEventListener('click',changeButtonImage);
});

Newly created button (by createElement("Button")) activates itself. How to stop that?

In hmtl file I have a simple button
<body>
<button type="button" onclick="create_button()">Create button</button>
</body>
and in js file I have two functions
function create_button() {
var new_button = document.createElement("Button");
new_button.innerHTML = "Pop the alert";
new_button.type = "button";
new_button.onClick = my_function();
document.body.appendChild(new_button);
};
function my_function() {
alert("Not so fast");
};
Obviously it should work in following manner:
Click Create button -> Pop the alert button appears
Click Pop an alert -> "Not so fast" alert appers
However after I click Create button, the alert appears. I guess that Pop an alert button activates itsef, but I don't know how to prevent it from doing so.
Edit. I actually have a problem in which my_function depends on some parameters.
So lets say we have following situation:
function my_function(x) {
alert("I like " + x);
};
and I want to create button which does my_function("Stack Overflow").
Based on this SO discussion I used
new_button.addEventListener('click', function(){my_function("Stack Overflow");});
and it works.
You can use new_button.addEventListener('click',my_function);. So my_function would be referenced, but not called imidiatley:
function create_button() {
var new_button = document.createElement("Button");
new_button.innerHTML = "Pop the alert";
new_button.type = "button";
new_button.addEventListener('click', my_function);
document.body.appendChild(new_button);
};
function my_function() {
alert("Not so fast");
};
<button type="button" onclick="create_button()">Create button</button>
After the edit
If your my_function have arguments, you have to wrap it into anonymous function, so it would be:
new_button.addEventListener('click',function(){
my_function(5);
});
Or
new_button.onclick=function(){
my_function(5);};
As extend to #itsgoingdown answer:
function create_button() {
var new_button = document.createElement("Button");
new_button.innerHTML = "Pop the alert";
new_button.type = "button";
new_button.addEventListener('click', function () {
var x = ' sport'
my_function(x)
});
document.body.appendChild(new_button);
};
function my_function(x) {
alert("Not so fast" + x);
};

Categories

Resources