calling a function from another function by 'onclick' event - javascript

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;

Related

Is there another way to add an onclick function on an input button?

I tried onclick function on the intSubmit but for some reason when the code is executed the onclick is called once and when you press the button it does nothing. I tried using "debug()" but that, as I figured, doesn't work at all.
if(qType === "INTEGER"){
let intAnswer = document.createElement("input");
intAnswer.type = "text";
intAnswer.id = "intA";
let intSubmit = document.createElement("input");
intSubmit.type = "button";
intSubmit.onclick = debug();
intSubmit.value = "Submit";
qDiv.appendChild(intAnswer);
qDiv.appendChild(intSubmit);
}
You are calling the method by using the (). Just pass the method as a parameter without calling it
intSubmit.onclick = debug;
you function is not bind properly, the way you binding function is wrong.
var qType = "INTEGER"
var clickCount=0
if(qType === "INTEGER"){
let intAnswer = document.createElement("input");
intAnswer.type = "text";
intAnswer.id = "intA";
let intSubmit = document.createElement("input");
intSubmit.type = "button";
intSubmit.onclick =test
intSubmit.value = "Submit";
qDiv.appendChild(intAnswer);
qDiv.appendChild(intSubmit);
}
function test(){
++clickCount
alert('click done:'+clickCount); };
<div id="qDiv"></div>

Fixing Issue in a simple text field value changer using basic HTML and JS

Need help making a simple text editor :
Text is displayed on screen
Click on Text to change it
Click change button to see the changes
but program goes in an infinite oop
var creators = {
hTag :function(textToInput){
var h1 = document.createElement('h1');
var div = document.getElementById('main');
div.innerHTML = '';
h1.id = 'userText';
h1.textContent = textToInput;
div.appendChild(h1);
console.log(div);
listeners.hTagListener();
//document.querySelector('h1');
//hTag.addEventListener('click',this.);
},
changeField :function(){
var input = document.createElement('input');
var button = document.createElement('button');
var div = document.getElementById('main');
div.innerHTML='';
button.id = 'changeButton';
button.textContent = 'Change';
input.id = 'input';
input.type = 'text';
div.appendChild(button);
div.appendChild(input);
listeners.changeButtonListener();
}
};
var listeners = {
hTagListener : function(){
var h1Print = document.querySelector('h1');
h1Print.addEventListener('click',creators.changeField());
console.log('added event listener');
},
changeButtonListener : function(){
var but = document.getElementById('changeButton');
var inputText = document.getElementById('input');
console.log(inputText.value);
but.addEventListener('click',creators.hTag(inputText.value));}
};
creators.hTag('initialValue');
and my Main HTML is
<body>
<br>
<br>
<div id="main">
</div>
<script src="/script.js" defer></script>
Expected :
In the last line of javascript, a header tag is appended to div
which has textContent 'initialValue'.
After Clicking on it :
A text Field and change button should appear,on clicking change, new Value must be displayed as Header!
Actual :
Program goes in an infinite loop!
While adding event listener you are calling actual function instead of that you should just bind the event the modified code is below
var listeners = {
hTagListener : function(){
var h1Print = document.querySelector('h1');
h1Print.addEventListener('click',creators.changeField);
console.log('added event listener');
},
changeButtonListener : function(){
var but = document.getElementById('changeButton');
var inputText = document.getElementById('input');
but.addEventListener('click',function(){creators.hTag(inputText.value)},false);
}
Currently addEventListener click methods are directly executing onload of the screen. Due to this execution is going for the infinite loop. To avoid this bind the method as below
var listeners = {
hTagListener : function(){
var h1Print = document.querySelector('h1');
h1Print.addEventListener('click',creators.changeField.bind(this), false);
console.log('added event listener');
},
changeButtonListener : function(){
var but = document.getElementById('changeButton');
var inputText = document.getElementById('input');
console.log(inputText.value);
but.addEventListener('click',creators.hTag.bind(this, inputText.value));
}
};

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

Only update added javascript elements on second click

I have some Javascript code that gets values from an array that processes a http response from a server and adds buttons to a modal window. So the ids for the buttons come from the array.
On second click everything is fine and my buttons are added to the modal window. But when I call the function the next time it adds the buttons again, but it should only update the buttons.
How can I handle it that the function will only update the buttons on second and further clicks?
buttonContainer = document.getElementById('modal1');
for (i = 0; i < resultContainers.length; i++) {
newButton = document.createElement('input');
newButton.type = 'button';
newButton.value = resultContainers[i];
newButton.id = resultContainerValues[i];
newButton.class = 'buttonContainer';
if (newButton.id == 'true') {
newButton.style.backgroundColor = '#8cff1a';
};
newButton.onclick = function () {
alert('You pressed '+this.id);
};
buttonContainer.appendChild(newButton);
You need to check if the button already exists before you add it in that case. Since you know the id of the button you're about to create, you can see if there's already a button with that id and just update it instead.
var newButton = document.getElementById(resultContainerValues[i]);
if(newButton!=null) {
newButton.value = resultContainers[i];
} else {
newButton = document.createElement('input');
newButton.type = 'button';
newButton.value = resultContainers[i];
newButton.id = resultContainerValues[i];
newButton.class = 'buttonContainer';
if (newButton.id == 'true') {
newButton.style.backgroundColor = '#8cff1a';
}
newButton.onclick = function () {
alert('You pressed '+this.id);
};
buttonContainer.appendChild(newButton);
}

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