/    Sign up×
Community /Pin to ProfileBookmark

Two Buttons exec the same function

Hey there!

I’m programatically and dynamically build a popup with one ore more action buttons which are defined in a javascript file.
In my example I’ve got two buttons, which I am assigning two different “click” functions. But it does not matter, which button I’ll click, they both execute the same function and I don’t know why:
Defining popup
`openPopup({
“title”: “my Popup”,
….
“options”:[
{
“label”:”Downside”,
“click”:function (e) {
alert(“Clicked downside button with id: ” + $(e.target).attr(“id”));
}
}, {
“label”:”Upside”,
“click”:function hoch(e) {
alert(“Clicked upside button with id: ” + $(e.target).attr(“id”));
}
}
]
});`

Far easy. And here is the popup builder.
`// Creating button container
var options = $(‘<div id=”overlay_box_footer”>’);
if (popbuilder.options != undefined)
{
for (option of popbuilder.options)
{
// Create new button
var button = $(“<button>”);
button.attr(“type”,”button”);
button.attr(“id”,”sampleId_” + (Math.random() * 1000));
button.click(function (e) {
// Calling defined callback function of my “action button” which is defined in first code and which should be dynamically in dependence of which button I’ve clicked. So this seems to be the faulty code
option.click(e);
});
// Setting label which is also defined above
button.append(option.label);
// Adding current button to outer container
options.append(button);
}
}`

Visually I’ve got two buttons, one named ‘Downside’ and one ‘Upside’. But it does not matter which of them I click, the displayed alert is always ‘Clicked upside button with id: sampleId_xxxx’ where xxxx is the id of the clicked button. But the wrong function is called.

Do you know why? Thanks a lot and kind regards!

to post a comment
JavaScript

1 Comments(s)

Copy linkTweet thisAlerts:
@daveyerwinJul 03.2020 — this ...

button.click(function (e) {

option.click(e);

});

should be ...

button.click(option.click);


now why is the second option function called by both buttons?

when the loop ends option still points to the second option

option.click(e) actually calls the click function in the second option

this is obviously not what you want
×

Success!

Help @Mike46 spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 4.26,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,

tipper: @Samric24,
tipped: article
amount: 1000 SATS,
)...