Reputation: 5742
I am trying to call a function when the form submit button is clicked. The page should not refresh, I want to add the category via AJAX.
The problem is that everything works fine when I add it manually to the html file, but when I try to add it in the javascript function via appendTo
, the click function is never called. What is the problem here?
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"> <input type="text" class="inptHtmlColor" placeholder="Hintergrund: #000FFF"> <input type="text" class="inptTextColor" placeholder="Text: #000FFF"><input type="button" value="Go" class="addCategoryBtn"></form></div>';
$(html).appendTo($('body'));
Upvotes: 4
Views: 197
Reputation: 22339
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 lower, 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 the append:
html += '<br><br><form id="addCategory_form" action=""><input type="text" class="inptCategoryName" placeholder="Kategorie Name"> <input type="text" class="inptHtmlColor" placeholder="Hintergrund: #000FFF"> <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');
});
Eitherway, what ever you do, try to avoid live()
Upvotes: 4