Submit form via jQuery not working

I am trying to call a function when the submit button is pressed. The page should not be updated, I want to add a category through AJAX.

The problem is that everything works fine when I add it manually to the html file, but when I try to add it to the javascript function via appendTo , the click function is never called. What is the problem?

JavaScript:

 $(".addCategoryBtn").click(function() { console.log('add category clicked'); }); 

Part of the JavaScript function:

 html += '<br><br><form id="addCategory_form" action=""><input type="text" class="inptCategoryName" placeholder="Kategorie Name">&nbsp;<input type="text" class="inptHtmlColor" placeholder="Hintergrund: #000FFF">&nbsp;<input type="text" class="inptTextColor" placeholder="Text: #000FFF"><input type="button" value="Go" class="addCategoryBtn"></form></div>'; $(html).appendTo($('body')); 
+4
source share
2 answers

For dynamic content when using jquery 1.7 or later use on () :

 $("body").on('click','.addCategoryBtn',function() { console.log('add category clicked'); }); 

For jQuery 1.6.x and below, including 1.4.3, use delegate () :

 $("body").delegate('.addCategoryBtn', 'click', function() { console.log('add category clicked'); }); 

For jQuery 1.4.2 or lower, use bind after adding:

 html += '<br><br><form id="addCategory_form" action=""><input type="text" class="inptCategoryName" placeholder="Kategorie Name">&nbsp;<input type="text" class="inptHtmlColor" placeholder="Hintergrund: #000FFF">&nbsp;<input type="text" class="inptTextColor" placeholder="Text: #000FFF"><input type="button" value="Go" class="addCategoryBtn"></form></div>'; $(html).appendTo($('body')); $(".addCategoryBtn").bind("click", function() { console.log('add category clicked'); }); 

In any case, whatever you do, try to avoid live ()

+4
source

Since a dynamic content event must be bound using the on function:

 $("body").on('click','.addCategoryBtn',function() { console.log('add category clicked'); }); 
+3
source

All Articles