How to get clicked button that was created dynamically? - javascript

I am trying to get a dynamically created button in order to access its parent.
I already tried to do:
var btn = document.createElement("BUTTON");
btn.innerHTML="Add";
addButton.appendChild(btn);
btn.addEventListener("click(this)", add);
sadly the button won't work if i type "click(this)". It only works if I type "click".
Changing the method to function add(element) from function add() also did not work.
How can i access the parent of my clicked button?
I cant create my buttons in HTML since i am creating a dynamic list of buttons which may differ depending on the size of the array.
Also my code should only be in Javascript
Thanks for the help!

By magic, I mean by the standard, the button reference is passed to the object.
function add() {
console.log(this);
}
var btn = document.createElement("BUTTON");
btn.innerHTML="Add";
addButton.appendChild(btn);
btn.addEventListener("click", add);
<div id="addButton"></div>
If you really wanted to pass along a variable
function add(btn, what) {
console.log(btn, what);
}
var btn = document.createElement("BUTTON");
btn.innerHTML="Add";
addButton.appendChild(btn);
btn.addEventListener("click", function(){ add(this,'foo'); });
<div id="addButton"></div>

Check this : https://www.w3schools.com/jsref/met_document_addeventlistener.asp
You should use btn.addEventListener("click", () => {}) instead of btn.addEventListener("click", () => {}).
But I think it would be better to use document.addEventListener((e) => {}) and then check the target (e.target)

Related

javascript automatic create button with individuell onclick event

i create a lot of listboxes and buttons with javascript.
each button should access a list box. The automatic create in a loop is not a problem. but the click event gives me problems.
normally i would:
var el = document.getElementById ('AButton');
el.onclick = DoFunction;
call this only with automatically created button?
How can I automatically create the DoFunction individually, so that it makes something individual for each button? So is it always the same only with individual controls?
function DoFunction(selectbox)
{
var i;
for(i=selectbox.options.length-1;i>=0;i--)
{
selectbox.remove(i);
}
}
try this:
btn.addEventListener("click", function(){
var btnTwo = document.createElement("BUTTON");
btnTwo.innerHTML = "button";
div.appendChild(btnTwo);
})
<button id="btn">click</button>
<div id="div"></div>

How to pass value of a button into a function when it's clicked

So I'm trying to create a quiz for a class of mine. I've created an array of objects to hold my questions, answers, and what the correct answer is. I'm using a forEach to generate buttons for each "answer" option at the specified index. I've added and onClick event to attempt to pass the value of the button into a function but I cannot seem to figure out what's the best way to go about doing this. I've included some of my code below to hopefully help.
var answers = quiz[index].answers;
answers.forEach(function(element) {
var optionButton = document.createElement("button");
optionButton.innerHTML = element;
optionButton.className = "btn";
optionButton.setAttribute("option-answer", element)
optionButton.setAttribute("onClick", "verifyAnswer()")
questionTitle.appendChild(optionButton);
})
just pass the argument in your function call. here i use arrow function:
optionButton.addEventListener("click", () => {verifyAnswer(element)})
Instead of making an onClick attribute, you could use an event listener to do additional actions when the button is clicked:
optionButton.addEventListener("click", function(){
verifyAnswer(currentIndex);
});
You could add the info using dataset and then recover it in the EventListener
const answers=["option 1","option 2","option 3"];
answers.forEach(function(element) {
let optionButton = document.createElement("button");
optionButton.innerHTML = element;
optionButton.className = "btn";
//Add data info
optionButton.dataset.answer=element;
optionButton.addEventListener("click", verifyAnswer);
document.getElementById("container").appendChild(optionButton);
})
function verifyAnswer(event){
clickedElement = event.target || event.srcElement;
//getting info in the element
alert(clickedElement.dataset.answer);
}
<div id="container">
</div>
Or if your answer data is the same as the text inside de button you can also use this
function verifyWithText(event){
clickedElement = event.target || event.srcElement;
alert(clickedElement.innerHTML);
}
Hope it helps
You could keep track of the answer index when creating a button, either via a data- attribute or directly in the function call.
var answers = quiz[index].answers;
answers.forEach(function(element, currentIndex) {
var optionButton = document.createElement("button");
optionButton.innerHTML = element;
optionButton.className = "btn";
optionButton.setAttribute("option-answer", element)
optionButton.setAttribute("onClick", "verifyAnswer(" + currentIndex + ")")
questionTitle.appendChild(optionButton);
})
And then, in your function call, you can retrieve the answer using a simple accessor.
function verifyAnswer(index) {
const answer = answers[index]
/* ... */
}
You can do it with passing argument in your verifyAnswer function
"verifyAnswer("+element+")"
where "element" is argument that you want to provide it can be anything.
The other way is with listener
optionButton.addEventListener('click', function(){
verifyAnswer(element);
});

How to return ID value from Click event function?

I am a beginner in Javascript.
I'm trying to get the ID of the clicked button.
I have used a function to get the ID, but I am unable to return the value.
How do I return the ID and use it outside?
the alert statement is for testing.
var getID = function(){
var ID=this.id;
alert(ID);
}
document.getElementById('button1').addEventListener('click',getID);
<button id="button1">Click Me!</button>
var getID = function(event){
var ID = event.target.getAttribute('id');
alert(ID);
}
var ID = event.currentTarger.id;
The this keyword refers to the current object that the current function is a part of.
At the base level where there appears to be no object, "document" is the actual object. It is an irrelevance to refer to "this" any further in relation to event handler which could be operating within any object and handling events from beyond the object.
Every event triggered has a number of standard attributes attached to it. "currentTarget" is the element upon which the event listener was triggered calling your event handling function.
So long as the event has an id, the element attribute "id" will tell you what that is.
var getID = function(event){
var elementWithID = event.currentTarget;
var ID = elementWithID.id;
alert(ID);
}
to put it in a more verbose style.
You can get a reference to source clicked element by using e.target.
Here is an simple example.
// get all buttons
const buttons = document.querySelectorAll('button')
// add click event listener to each button
buttons.forEach(button => {
button.addEventListener('click', e => {
console.log(`id -> ${e.target.id}`)
})
})
<button id="hello">Hello</button>
<button id="world">World</button>
<button id="i-am">I'm</button>
<button id="happy">Happy</button>

How to get id of clicked button in winjs

I have several buttons in my WinJS page.
<button id="btn1">
Button 1
</button>
<button id="btn2"">
button 2
</button>...
and javascript to add click event to clicked button:
(function () {
WinJS.UI.processAll().done(function () {
var showButton = document.querySelector("xxx");
showButton.addEventListener("click", function () {
});
});
})();
How do i determine what button is clicked and set value of "xxx" to id of that button (btn1, btn2 etc...)
If I understood you correctly, you want to identify the button (sender) when you have multiple buttons that are attached to a single event handler.
MSDN:
In JavaScript, Windows Runtime event arguments are represented as a
single event object. In the following example of an event handler
method, the ev parameter is an object that contains both the sender
(the target property) and the other event arguments. The event
arguments are the ones that are documented for each event.
So you need to define an argument for the event handler and use its target property.
Let's say you have the following HTML:
<div id="label1"/>
<div>
<button id="button1">Button1</button><br />
<button id="button2">Button2</button><br />
<button id="button3">Button3</button><br />
</div>
and attached a single event handler to all of the buttons:
var button1 = document.getElementById("button1");
button1.addEventListener("click", buttonClickHandler);
var button2 = document.getElementById("button2");
button2.addEventListener("click", buttonClickHandler);
var button3 = document.getElementById("button3");
button3.addEventListener("click", buttonClickHandler);
you can access to sender in this way:
function buttonClickHandler(eventInfo) {
var clickedButton = eventInfo.target;
var label1 = document.getElementById("label1");
label1.innerHTML = clickedButton.id.toString();
}
Here's a WinJS solution to get the buttons :
var buttons = WinJS.Utilities.query('button');
Then you can bind the event to the buttons click :
buttons.forEach(function (btn) {
btn.addEventListener("click", function () {
console.log('button ' + this.id + ' has been clicked.');
})
});
I am new to WinJS, so there is probably a prettier solution to replace the forEach.
Something like this should work. querySelector only returns the first match, so you need to use querySelectorAll (see docs).
var buttons = document.querySelectorAll("button");
for (var i = 0; i < buttons.length; i++) {
buttons[i].addEventListener("click", function () {
var id = this.id;
// do stuff with "id"
});
}
You might also consider looking into jQuery as that can make things like this a little bit cleaner.

how to call onclick function on dynamically created button in javascript

var del = document.createElement('input');
del.type = 'button';
del.name = 'delll';
del.value = 'del';
del.onClick = 'alert("hi javascript")';
Here I have dynamically created a input type BUTTON and now I want to call function on button click event. I am using onClick(); function for this. In the above code all is working fine but del.onclick is not working as I want (for generating alert for demo)
I am not using any jquery code in this program so please don't use any jquery code.
set the onclick (all lower case) to an anonymous function
del.onclick = function(){ alert('hi javascript');};
note the function is not in quotes like other attributes
del.onclick = function () {
alert("hi jaavscript");
};
Use small "C" in onClick and pass a function for it.
Demo here
Try like this
var del = document.createElement('input');
del.setAttribute('type', 'button');
del.setAttribute('name', 'delll');
del.setAttribute('value', 'del');
del.setAttribute('onClick', 'alert("hi jaavscript")');
So to answer the question in details:
del.onclick = '' does not "execute" something within quotes.
If you want to execute/call a function, you would want to pass the function as a parameter.
i.e
del.onclick = function() { alert('hi there!')}

Categories

Resources