Trying to add onclick function to a button created in Javascript - javascript

I have a button created through javascript but I can't assign the function to the button.
The function works when I make it an onclick not assigned to any button so I know I'm probably formatting something wrong.
Any help is appreciated.
JS code
var tickButton;
for (tickButton = 0; tickButton < myNodelist.length; tickButton++) {
var span = document.createElement("SPAN");
var txt = document.createTextNode("\u2713");
span.className = "tick";
span.appendChild(txt);
tickButton.onclick = function(){
alert('hello');
};
myNodelist[tickButton].appendChild(span);
}

I guess you can use this code :
let btn = document.createElement("button");
btn.innerHTML = "Save";
btn.onclick = function () {
alert("Button is clicked");
};
document.body.appendChild(btn);
or
let btn = document.createElement("button");
btn.innerHTML = "Save";
btn.addEventListener("click", function () {
alert("Button is clicked");
});
document.body.appendChild(btn);
But I suggest using onClick, it's a better way to do it.
Also, be aware that you should add the whole code in your loop. Since you must not be looping on the variable that contain the button.
Source : https://sebhastian.com/javascript-create-button/

You are adding the onclick to your iterator. Add it to your span instead:
var tickButton;
var myNodelist = document.querySelectorAll('#crudList li');
for (tickButton = 0; tickButton < myNodelist.length; tickButton++) {
var span = document.createElement("SPAN");
var txt = document.createTextNode("\u2713");
span.className = "tick";
span.appendChild(txt);
span.addEventListener(
"click",
function(){
alert('hello');
}
);
myNodelist[tickButton].appendChild(span);
}
<ul id="crudList">
<li>1</li>
<li>2</li>
<li>3</li>
</ul>

Related

Onclick "run a function" using external javascript

I created a simple project in which I click on a button then another button should be created(button 2) and the previous button should be disappeared and this works fine.
But when I click on button 2 then a particular function should be executed. I am stuck here.
It says cannot set property to null.
function myFunction1() {
var x = document.createElement("BUTTON");
var t = document.createTextNode("button 2");
x.setAttribute('id','bt2');
x.appendChild(t);
document.body.appendChild(x);
var a= document.getElementById('bt1');
a.style.display='none';
}
var item = document.getElementById('bt2');
item.onclick = myFunction;
function myFunction() {
document.getElementsByTagName("BODY")[0].style.backgroundColor = "lime";
}
<button id= 'bt1' onclick="myFunction1();">
button 1
</button>
You are trying to set the onclick property to an element when it doesn't exist yet in the DOM (it will be created after you click the button 1), so move the final code inside the myFunction1, after the creation of the second button.
function myFunction1() {
var b = document.body;
var x = document.createElement("button");
var t = document.createTextNode("button 2");
x.id = 'bt2';
x.appendChild(t);
b.appendChild(x);
var btt1 = document.getElementById('bt1');
btt1.style.display='none';
var btt2 = document.getElementById('bt2');
btt2.addEventListener('click', function() {
b.style.backgroundColor = "lime";
});
}
<button id= 'bt1' onclick="myFunction1();">
button 1
</button>

onclick excecutes does not work, only when creating DOM

I have the following HTML and javascript.
I can create the buttons without any problem, but the onclick function does not work when clicking the button. It does not do anything.
If I put the method without the ' it excecutes when generating the form, one after the other generating 3 dialogs
function makeUL(array) {
var list = document.createElement('ul');
for (var i = 0; i < array.length; i++) {
var btn = document.createElement("BUTTON");
/*
btn.onClick = function () {
buttonClicked(array[i]);
};*/
var t = document.createTextNode(array[i]); // Create a text node
btn.appendChild(t); // Append the text to <button>
btn.type = "button"
btn.onClick = 'buttonClicked()';
list.appendChild(btn); // Append <button> to <body>
var nextLine = document.createElement("td");
list.appendChild(nextLine);
}
return list;
}
/*
function buttonClicked(buttonName){
alert(buttonName);
}*/
function buttonClicked() {
alert("algo");
}
self.onInit = function() {
var boton = [];
for (var g = 0; g < self.ctx.settings.Botones.length; g++) {
boton[0] = self.ctx.settings.Botones[g].btnId;
boton[1] = self.ctx.settings.Botones[g].method;
boton[2] = self.ctx.settings.Botones[g].params;
document.getElementById('myList').appendChild(makeUL(boton));
}
self.ctx.$scope.sendCommand = function() {
var timeout = self.ctx.settings.requestTimeout;
var rpcMethod = self.ctx.settings.method;
var rpcParams = self.ctx.settings.params;
var commandPromise;
commandPromise = self.ctx.controlApi.sendTwoWayCommand(rpcMethod, rpcParams, timeout);
commandPromise.then(
function success(response) {
//alert("Comando recibido exitosamente\n Respuesta:" + angular.toJson(response));
alert("Comando recibido exitosamente");
},
function fail(rejection) {
alert("ERROR AL ENVIAR COMANDO");
}
);
};
};
<form name="rpcForm">
<md-content class="md-padding" layout="column">
<div id="myList"></div>
</md-content>
</form>
The problem is:
btn.onClick = 'buttonClicked()';
It looks like you were trying to assign to the onclick attribute of the HTML, in which case the proper syntax would be
btn.setAttribute('onclick', 'buttonClicked()');
But since you already have a reference to the element, there's no need to resort to attributes; inline handlers are pretty bad practice anyway. Change to:
btn.onclick = buttonClicked;
(note the lower-case c in onclick), or
btn.addEventListener('click', buttonClicked);
Also, you might consider simply assigning to the button's textContent rather than creating a text node explicitly, it's a bit easier to read and write: change
var t = document.createTextNode(array[i]); // Create a text node
btn.appendChild(t); // Append the text to <button>
to
btn.textContent = array[i];

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

Calling a function before callback function

I'm making to-do app and trying to run one function which is supposed to ran before callback function returns output. Callback fn is listening to click event and outputs user's input value to the screen. But before it happens, I want to first output h1 element on top with some text and then return callback function. How can I do this? I tried to use setInterval on the callback, but it didn't help. If user types something and clicks the add button, I want text "to-do list" appear on the most top and then after that the actual user's input itself. My code:
(function () {
var button = document.getElementsByTagName("button");
var userInput = document.getElementById("user_input");
function addItem() {
var li = document.createElement("li");
li.innerHTML = userInput.value;
document.getElementsByTagName("ul")[0].appendChild(li);
userInput.value = "";
}
function categorize() {
console.log(document.getElementById("todo").getElementsByTagName('li').length);
if (document.getElementById("todo").getElementsByTagName('li').length > 0 && document.getElementById("todo").getElementsByTagName('li').length < 2) {
var h1 = document.createElement("h1");
h1.innerHTML = "to-do";
document.getElementById("todo").appendChild(h1);
}
}
button[0].addEventListener("click", addItem, false);
button[0].addEventListener("click", categorize);
})();
Well there are some questions that needs to get answers here:
Why don't you just call categorize() function in the addItem and
use only addItem() as callback.
Why are you wrapping your whole code in an Immediately-Invoked Function Expression?
Why are you only showing the h1 element if there's only one element in the Todo list?
I tried to refactor your code so it makes more sense. This is a working Demo:
var button = document.getElementsByTagName("button");
var userInput = document.getElementById("user_input");
var entered = false;
function addItem() {
if(!entered){
categorize();
}
var li = document.createElement("li");
li.innerHTML = userInput.value;
document.getElementsByTagName("ul")[0].appendChild(li);
userInput.value = "";
}
function categorize() {
entered= true;
var h1 = document.createElement("h1");
h1.id = "title";
h1.innerHTML = "to-do";
document.getElementById("todo").appendChild(h1);
}
button[0].addEventListener("click", addItem, false);
<input type="text" id="user_input" />
<button>Add Item</button>
<div id="todo">
<ul></ul>
</div>
Try this :
button[0].addEventListener("click", function () { categorize(); addItem(); });
instead of this :
button[0].addEventListener("click", addItem, false);
button[0].addEventListener("click", categorize);
My suggestion is handling event mousedownthat is fired before click event
button[0].addEventListener.on('mousedown', categorize);
I have made minor updates to you code below. Please try and use this instead.
(function () {
var button = document.getElementsByTagName("button");
var userInput = document.getElementById("user_input");
function categorize() {
console.log(document.getElementById("todo").getElementsByTagName('li').length);
if (document.getElementById("todo").getElementsByTagName('li').length > 0 && document.getElementById("todo").getElementsByTagName('li').length < 2) {
var h1 = document.createElement("h1");
h1.innerHTML = "to-do";
document.getElementById("todo").appendChild(h1);
}
}
function addItem() {
categorize(); //since you want this to be executed before the code in addItem()
var li = document.createElement("li");
li.innerHTML = userInput.value;
document.getElementsByTagName("ul")[0].appendChild(li);
userInput.value = "";
}
button[0].addEventListener("click", addItem);
})()

How to set a javascript function to an element with no postback

I created an input type=file and I need to connect it to my Javascript function, the problem is that I get postback (I don't need server-side), I tried different ways (code below).. maybe I set the function wrong... Help please
++ createMyButton is fired from another function and works fine.
//JAVASCRIPT
function createMyButton(){
var deleteBtn = document.createElement('input');
deleteBtn.type = "button";
deleteBtn.title = "Delete";
//1 try
deleteBtn.onclick = 'deleteItem()';
//2 try
deleteBtn.onclick = 'deleteItem();return false';
}
//FUNCTION
function deleteItem() {
alert("delete");
}
These are the issue I seen
1.deleteBtn.onclick = 'deleteItem();' are you missing quote "''here ?
2
. If u want to bind event to element use addEventListener to for
E.g
var deleteBtn = document.createElement('input');
deleteBtn.type = "button";
deleteBtn.title = "Delete";
// you missed button value here
deleteBtn.value = "Delete";
deleteBtn.addEventListener('click', deleteItem);
//FUNCTION
function deleteItem() {
var btn = this; // you can use button here
alert("delete");
}
JSBIN EXAMPLE

Categories

Resources