Why does this javascript function activate at the wrong time? - javascript

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

Related

Trying to add onclick function to a button created in 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>

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];

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

calling a function from another function by 'onclick' event

What I am trying to do is, call a function from another function by clicking a radio button in that function. Here is the code I have worked on so far-
<script type="text/javascript">
rad1 = document.createElement("input");
rad1.type = "radio";
rad1.name = "dooropt";
rad1.id = "rb1";
rad1.value = "y";
newP.appendChild(rad1);
text1 = document.createTextNode("Yes ");
newP.appendChild(text1);
rad2 = document.createElement("input");
rad2.type = "radio";
rad2.name = "dooropt";
rad2.id = "rb2";
rad2.value = "n";
newP.appendChild(rad2);
text2 = document.createTextNode("No ");
newP.appendChild(text2);
button1 = document.createElement("input");
button1.type = "button";
button1.value = "Open main door";
button1.style.visibility = "hidden";
newP.appendChild(button1);
button2 = document.createElement("input");
button2.type = "button";
button2.value = "Open apartment door";
button2.style.visibility = "hidden";
newP.appendChild(button2);
area.appendChild(newP);
rad1.onclick = mainalso();
rad2.onclick = onlyapp();
}
function mainalso()
{
button1.style.visibility="visible";
button2.style.visibility="visible";
}
function onlyapp()
{
button2.style.visibility="visible";
button1.style.visibility="hidden";
}
</script>
Now, whenever rad1 is clicked, i want mainalso() to run, as might be clear from the code. Since I am fairly new to JavaScript, I don't know where i'm making the mistake, in syntax or conceptually. Also, the first function (before mainalso()) is add(), and in it I repeatedly append same content on clicking a button in my body. I hope it is clear what I want to do. When rad1 is clicked, i want both buttons (button1 and button2) to appear, but on clicking rad2 I want only one button to appear. Both have been set to 'hidden' visibility at first.
Please help me out. Sorry if it seems unclear, I tried my best..
Thank you.
Try changing:
rad1.onclick = mainalso();
rad2.onclick = onlyapp();
To:
rad1.onclick = mainalso;
rad2.onclick = onlyapp;
As it stands you're assigning the result of calling the functions to the onclick of rad1 and rad2 which in this case will be undefined. By removing the () you will assign the function correctly.
To ensure that button1 and button2 are available and set to the correct value when your function is called you could change the code to:
...
newP.appendChild(button2);
area.appendChild(newP);
(function (b1, b2) {
rad1.onclick = function () {
b1.style.visibility="visible";
b2.style.visibility="visible";
};
rad2.onclick = function () {
b2.style.visibility="visible";
b1.style.visibility="hidden";
};
})(button1, button2);
You should do this:
rad1.onclick = mainalso;
rad2.onclick = onlyapp;
Edit: I tried this and it works for me. See example
window.onload = function() {
rad1 = document.createElement("input");
rad1.type = "radio";
rad1.name = "dooropt";
rad1.id = "rb1";
rad1.value = "y";
newP.appendChild(rad1);
text1 = document.createTextNode("Yes ");
newP.appendChild(text1);
rad2 = document.createElement("input");
rad2.type = "radio";
rad2.name = "dooropt";
rad2.id = "rb2";
rad2.value = "n";
newP.appendChild(rad2);
text2 = document.createTextNode("No ");
newP.appendChild(text2);
button1 = document.createElement("input");
button1.type = "button";
button1.value = "Open main door";
button1.style.visibility = "hidden";
newP.appendChild(button1);
button2 = document.createElement("input");
button2.type = "button";
button2.value = "Open apartment door";
button2.style.visibility = "hidden";
newP.appendChild(button2);
area.appendChild(newP);
rad1.onclick = mainalso();
rad2.onclick = onlyapp();
}
You have to define newP and area that you are using :
area.appendChild(newP);
As the tag HTML is used like this :
<input type="radio" name="dooropt" id="rb1" value="y" onClick="mainalso()"/>
So you can use :
rad1.onClick=mainalso;

Categories

Resources