Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery .click() not working?

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?

like image 311
Bandara Avatar asked Jan 06 '17 04:01

Bandara


People also ask

Why is my jQuery click function not working?

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.

Why is click not working?

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.

What is $( function () in jQuery?

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() { });

Is not defined in jQuery?

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.


2 Answers

Try this:

$(document).on('click', '.download', function(){ 
     // Your Code
});
like image 134
Sahadev Avatar answered Nov 06 '22 18:11

Sahadev


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.

like image 20
Jai Avatar answered Nov 06 '22 18:11

Jai