I generate the set of buttons within html table as follows and then I want to call to function when it click.
$.each(childData, function(key, item) {
var packPath = key.replace(/_/g, "/"); //Replace underscore with slash
div.innerHTML = div.innerHTML + '<td>'+key+'</td>'
+ '<td><button type="button" data-id="'+key+'" class="download btn btn-success btn-xs">Originals</li></td></div>';
})
This is how I call the function but it's not working.
$(".download").click(function(){
alert();
});
Where is the wrong in above code?
So Why Does It Happen? JQuery OnClick Method is bound to an element or selector on page ready/load. Therefore if that element you want to click isn't there at the time of page ready, the binding can't happen.
On Windows 10, head to Settings > Devices > Mouse. Under “Select your primary button,” ensure the option is set to “Left.” On Windows 7, head to Control Panel > Hardware and Sound > Mouse and ensure “Switch primary and secondary buttons” isn't checked. The ClickLock feature can also cause strange issues.
jQuery (a library built on Javascript) has built in functions that generally required the DOM to be fully rendered before being called. The syntax for when this is completed is: $(document). ready(function() { });
You may experience the “jQuery is not defined error” when jQuery is included but not loaded. Make sure that it's loaded by finding the script source and pasting the URL in a new browser or tab. The snippet of text you should look for to find the URL to test.
Try this:
$(document).on('click', '.download', function(){
// Your Code
});
Delegate the event to static parent:
$(div).on("click", ".download", function(){
Here div
can be the static parent which was available when page was loaded at first load. Although document
or body
can also be used in place of div
.
As you have not presented how you create div
element but one thing has to be noticed that you are generating an invalid markup. As a td
element can't be a child of div
but table
's tr
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With