Reputation: 309
I have a dynamic button, that loads when a condition in the JavaScript is fulfilled. When the Button loads, I need to invoke a function (ClickMe) which works as soon as I click the button.
Now the problem is I am not able to relate the function with the button.
In my code
var showthelocation = "";
showthelocation += '<li>';
if (data.location == 'Sydney'){
showthelocation += "</br><button class=\"" + ClickMe + "\">Show</button>";
}
showthelocation += '</li>';
function ClickMe("Click"){
//Some Code
};
$(".showthelocation").html(showthelocation);
and HTML
<ul class="showthelocation"></ul>
I want to put a ID or Class to access it from the ClickMe function, not able to do it. Any help?
Upvotes: 0
Views: 99
Reputation: 23322
Why not doing something like:
var showthelocation = "";
showthelocation += '<li>';
if (data.location == 'Sydney'){
showthelocation += '<br /><button onclick="ClickMe();">Show</button>';
}
showthelocation += '</li>';
$(".showthelocation").html(showthelocation);
function ClickMe(){
console.log("Some Code");
};
Or more jQuery'sh
...
showthelocation += '<br /><button id="myButton">Show</button>';
...
$(".showthelocation").html(showthelocation);
$("#myButton").onclick(ClickMe);
This works, but if you have more buttons that will execute the same function you should go for a class
instead of an id
, for example:
...
showthelocation += '<br /><button class="myButton">Show</button>';
...
$(".showthelocation").html(showthelocation);
$(".myButton").onclick(ClickMe);
This would attach the click handler to all buttons with the class myButton
.
Upvotes: 2
Reputation: 8610
I'm guessing your issue is with the ClickMe function on each button. Right now it's just writing out some sort of "[Object function]" thing in the HTML, I'm guessing. I think the best solution would be with a multi-part assignment. Remove the onclick from the HTML itself, then...
$(".showthelocation").html(showthelocation);
$(".showthelocation li button").onclick(ClickMe);
This should add the handlers to any and all buttons created that way.
Upvotes: 0